forked from tobischo/gokeepasslib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuuid.go
56 lines (49 loc) · 1.32 KB
/
uuid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package gokeepasslib
import (
"crypto/rand"
"encoding/base64"
"errors"
)
// ErrInvalidUUIDLength is an error which is returned during unmarshaling if the UUID does not have 16 bytes length
var ErrInvalidUUIDLength = errors.New("gokeepasslib: length of decoded UUID was not 16")
// UUID stores a universal identifier for each group+entry
type UUID [16]byte
// NewUUID returns a new randomly generated UUID
func NewUUID() UUID {
var id UUID
rand.Read(id[:])
return id
}
// Compare allowes to check whether two instance of UUID are equal in value.
// This is used for searching a uuid
func (u UUID) Compare(c UUID) bool {
for i, v := range c {
if u[i] != v {
return false
}
}
return true
}
// MarshalText is a marshaler method to encode uuid content as base 64 and return it
func (u UUID) MarshalText() ([]byte, error) {
text := make([]byte, 24)
base64.StdEncoding.Encode(text, u[:])
return text, nil
}
// UnmarshalText unmarshals a byte slice into a UUID by decoding the given data from base64
func (u *UUID) UnmarshalText(text []byte) error {
id := make([]byte, base64.StdEncoding.DecodedLen(len(text)))
length, err := base64.StdEncoding.Decode(id, text)
if err != nil {
return err
}
if length == 0 {
*u = NewUUID()
return nil
}
if length != 16 {
return ErrInvalidUUIDLength
}
copy((*u)[:], id[:16])
return nil
}