Debian Codegraph @

uuid.go

raw symbols SCIP
1 package gatt
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "encoding/hex"
7 "fmt"
8 "strings"
9 )
10
11 // A UUID is a BLE UUID.
12 type UUID struct {
13 // Hide the bytes, so that we can enforce that they have length 2 or 16,
14 // and that they are immutable. This simplifies the code and API.
15 b []byte
16 }
17
18 // UUID16 converts a uint16 (such as 0x1800) to a UUID.
19 func UUID16(i uint16) UUID {
20 b := make([]byte, 2)
21 binary.LittleEndian.PutUint16(b, i)
22 return UUID{b}
23 }
24
25 // ParseUUID parses a standard-format UUID string, such
26 // as "1800" or "34DA3AD1-7110-41A1-B1EF-4430F509CDE7".
27 func ParseUUID(s string) (UUID, error) {
28 s = strings.Replace(s, "-", "", -1)
29 b, err := hex.DecodeString(s)
30 if err != nil {
31 return UUID{}, err
32 }
33 if err := lenErr(len(b)); err != nil {
34 return UUID{}, err
35 }
36 return UUID{reverse(b)}, nil
37 }
38
39 // MustParseUUID parses a standard-format UUID string,
40 // like ParseUUID, but panics in case of error.
41 func MustParseUUID(s string) UUID {
42 u, err := ParseUUID(s)
43 if err != nil {
44 panic(err)
45 }
46 return u
47 }
48
49 // lenErr returns an error if n is an invalid UUID length.
50 func lenErr(n int) error {
51 switch n {
52 case 2, 16:
53 return nil
54 }
55 return fmt.Errorf("UUIDs must have length 2 or 16, got %d", n)
56 }
57
58 // Len returns the length of the UUID, in bytes.
59 // BLE UUIDs are either 2 or 16 bytes.
60 func (u UUID) Len() int {
61 return len(u.b)
62 }
63
64 // String hex-encodes a UUID.
65 func (u UUID) String() string {
66 return fmt.Sprintf("%x", reverse(u.b))
67 }
68
69 // Equal returns a boolean reporting whether v represent the same UUID as u.
70 func (u UUID) Equal(v UUID) bool {
71 return bytes.Equal(u.b, v.b)
72 }
73
74 // reverse returns a reversed copy of u.
75 func reverse(u []byte) []byte {
76 // Special-case 16 bit UUIDS for speed.
77 l := len(u)
78 if l == 2 {
79 return []byte{u[1], u[0]}
80 }
81 b := make([]byte, l)
82 for i := 0; i < l/2+1; i++ {
83 b[i], b[l-i-1] = u[l-i-1], u[i]
84 }
85 return b
86 }