-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprefixed.go
More file actions
83 lines (64 loc) · 1.77 KB
/
prefixed.go
File metadata and controls
83 lines (64 loc) · 1.77 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
package prefixed
import (
"encoding/base32"
"errors"
"strings"
"github.com/lsl/uuid"
)
var encoder = base32.NewEncoding("0123456789abcdefghjkmnpqrstvwxyz").WithPadding(base32.NoPadding)
func Encode(prefix string, u uuid.UUIDv7) string {
// Pre-allocate buffer: prefix + '_' + 26 base32 chars
result := make([]byte, len(prefix)+1+26)
copy(result, prefix)
result[len(prefix)] = '_'
// Encode directly into the buffer after the prefix and underscore
encoder.Encode(result[len(prefix)+1:], u[:])
return string(result)
}
func New(prefix string) string {
u := uuid.NewV7()
return Encode(prefix, u)
}
func Parse(input string) (prefix, encodedUUID string, err error) {
if input == "" {
return "", "", errors.New("input cannot be empty")
}
var found bool
prefix, encodedUUID, found = strings.Cut(input, "_")
if !found {
return "", "", errors.New("invalid format: missing underscore separator")
}
if len(encodedUUID) != 26 {
// 128 bits = 16 bytes → ceil(16 * 8 / 5) = 26 base32 characters
return "", "", errors.New("invalid encoded UUID length: must be 26 base32 characters")
}
return prefix, encodedUUID, nil
}
func Decode(input string) (string, uuid.UUIDv7, error) {
prefix, encodedUUID, err := Parse(input)
if err != nil {
return "", uuid.UUIDv7{}, err
}
var result uuid.UUIDv7
n, err := encoder.Decode(result[:], []byte(encodedUUID))
if err != nil {
return "", uuid.UUIDv7{}, errors.New("invalid base32 encoding")
}
if n != 16 {
return "", uuid.UUIDv7{}, errors.New("decoded UUID has invalid length")
}
return prefix, result, nil
}
func Validate(input string) bool {
if input == "" {
return false
}
_, encodedUUID, found := strings.Cut(input, "_")
if !found {
return false
}
if len(encodedUUID) != 26 {
return false
}
return true
}