-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfuid.go
More file actions
104 lines (90 loc) · 2.16 KB
/
fuid.go
File metadata and controls
104 lines (90 loc) · 2.16 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package fuid
import (
"encoding/base64"
"fmt"
"github.com/google/uuid"
)
var b64 = base64.RawURLEncoding
var Nil = FUID(uuid.Nil)
// FUID is a mirror or Google's UUID implementation with a short and
// friendly representation.
type FUID [16]byte
// New returns a Version 7 UUID based on the current time(Unix Epoch).
func New() FUID {
return FUID(uuid.Must(uuid.NewV7()))
}
// MustParse is like Parse but panics if the string cannot be parsed.
func MustParse(s string) FUID {
u, err := Parse(s)
if err != nil {
panic(`fuid: Parse(` + s + `): ` + err.Error())
}
return u
}
// Parse decodes s into a FUID or returns an error if it cannot be parsed.
func Parse(s string) (FUID, error) {
switch len(s) {
case 22:
b, err := b64.DecodeString(s)
if err != nil {
return Nil, err
}
return FUID(b), nil
case 22 + 2:
b, err := b64.DecodeString(s[1:23])
if err != nil {
return Nil, err
}
return FUID(b), nil
default:
gu, err := uuid.Parse(s)
return FUID(gu), err
}
}
// ParseBytes is like Parse, except it parses a byte slice instead of a string.
func ParseBytes(b []byte) (FUID, error) {
switch len(b) {
case 22:
var fu FUID
_, err := b64.Decode(fu[:], b)
return fu, err
default:
uu, err := uuid.ParseBytes(b)
return FUID(uu), err
}
}
// MarshalText implements encoding.TextMarshaler.
func (fu FUID) MarshalText() ([]byte, error) {
var buf [22]byte
b64.Encode(buf[:], fu[:])
return buf[:], nil
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (fu *FUID) UnmarshalText(data []byte) error {
id, err := ParseBytes(data)
if err != nil {
return err
}
*fu = id
return nil
}
// MarshalBinary implements encoding.BinaryMarshaler.
func (fu FUID) MarshalBinary() ([]byte, error) {
return fu[:], nil
}
// UnmarshalBinary implements encoding.BinaryUnmarshaler.
func (fu *FUID) UnmarshalBinary(data []byte) error {
if len(data) != 16 {
return fmt.Errorf("invalid UUID (got %d bytes)", len(data))
}
copy(fu[:], data)
return nil
}
// String returns the 22-character string form.
func (fu FUID) String() string {
return b64.EncodeToString(fu[:])
}
// UUID converts to raw UUID.
func (fu FUID) UUID() uuid.UUID {
return uuid.UUID(fu)
}