This repository was archived by the owner on Aug 5, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathuuid.go
More file actions
112 lines (101 loc) · 2.21 KB
/
Copy pathuuid.go
File metadata and controls
112 lines (101 loc) · 2.21 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
105
106
107
108
109
110
111
112
package typeid
import (
"database/sql/driver"
"fmt"
"github.com/google/uuid"
)
// UUID is a type-safe UUIDv7 identifier with a compile-time prefix.
// Maps to Postgres uuid.
type UUID[P Prefixer] struct {
val uuid.UUID
}
func NewUUID[P Prefixer]() (UUID[P], error) {
u, err := uuid.NewV7()
if err != nil {
return UUID[P]{}, err
}
return UUID[P]{val: u}, nil
}
func UUIDFrom[P Prefixer](u uuid.UUID) (UUID[P], error) {
if u.Version() != 7 {
return UUID[P]{}, ErrOnlyV7
}
return UUID[P]{val: u}, nil
}
func ParseUUID[P Prefixer](s string) (UUID[P], error) {
suffix, err := splitTypeid[P](s, uuidSuffixLen)
if err != nil {
return UUID[P]{}, err
}
b, err := decodeBase32UUID(suffix)
if err != nil {
return UUID[P]{}, err
}
u := uuid.UUID(b)
if u.Version() != 7 {
return UUID[P]{}, ErrOnlyV7
}
return UUID[P]{val: u}, nil
}
func (id UUID[P]) appendText(dst []byte) []byte {
var p P
return appendBase32UUID(dst, p.Prefix(), id.val)
}
func (id UUID[P]) String() string {
var buf [64]byte
return string(id.appendText(buf[:0]))
}
func (id UUID[P]) UUID() uuid.UUID { return id.val }
func (id UUID[P]) IsZero() bool { return id.val == uuid.UUID{} }
func (id UUID[P]) MarshalText() ([]byte, error) {
if id.IsZero() {
return nil, ErrZeroUUID
}
return id.appendText(nil), nil
}
func (id *UUID[P]) UnmarshalText(data []byte) error {
parsed, err := ParseUUID[P](string(data))
if err != nil {
return err
}
*id = parsed
return nil
}
func (id UUID[P]) Value() (driver.Value, error) {
if id.IsZero() {
return nil, ErrZeroUUID
}
return id.val.String(), nil
}
// Any converts a typed UUID to an AnyUUID with the same prefix and value.
func (id UUID[P]) Any() AnyUUID {
var p P
return AnyUUID{val: id.val, prefix: p.Prefix()}
}
func (id *UUID[P]) Scan(src any) (err error) {
var u uuid.UUID
switch v := src.(type) {
case string:
if u, err = uuid.Parse(v); err != nil {
return err
}
case []byte:
switch {
case len(v) == 16:
copy(u[:], v)
default:
if u, err = uuid.ParseBytes(v); err != nil {
return err
}
}
case [16]byte:
u = uuid.UUID(v)
default:
return fmt.Errorf("typeid: cannot scan %T into UUID", src)
}
if u.Version() != 7 {
return ErrOnlyV7
}
id.val = u
return nil
}