-
Notifications
You must be signed in to change notification settings - Fork 0
/
sortable.go
82 lines (66 loc) · 1.79 KB
/
sortable.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
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
package typeid
import (
"database/sql/driver"
"github.com/gofrs/uuid/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/sumup/typeid/base32"
)
// Sortable represents an unique identifier that is k-sortable.
// Internally, it's based on UUIDv7.
type Sortable[P Prefix] struct{ typedID[P] }
var sortableIDProc = &processor{
b32Encode: func(u uuid.UUID) string {
return base32.EncodeLower([16]byte(u))
},
b32EncodeTo: func(dst []byte, u uuid.UUID) {
base32.EncodeLowerTo(dst, [16]byte(u))
},
b32Decode: func(s string) (uuid.UUID, error) {
decoded, err := base32.DecodeLower(s)
if err != nil {
return uuid.Nil, err
}
return uuid.FromBytes(decoded)
},
generateUUID: uuid.NewV7,
}
func (Sortable[P]) processor() *processor {
return sortableIDProc
}
func (Sortable[P]) Type() string {
return getPrefix[P]()
}
func (s Sortable[P]) String() string {
return toString[P](s.uuid, s.processor())
}
func (r Sortable[P]) UUID() uuid.UUID {
return r.uuid
}
// MarshalText implements the [encoding.TextMarshaler] interface.
// Internally it use [Random.String]
func (r Sortable[P]) MarshalText() ([]byte, error) {
return marshalText(r)
}
// UnmarshalText implements the [encoding.TextUnmarshaler] interface.
// It parses a TypeID string using [FromString]
func (r *Sortable[P]) UnmarshalText(text []byte) error {
return unmarshalText(r, text)
}
func (s Sortable[P]) Value() (driver.Value, error) {
return value(s)
}
func (s *Sortable[P]) Scan(src any) error {
return scan(s, src)
}
func (s Sortable[P]) TextValue() (pgtype.Text, error) {
return textValue(s)
}
func (s *Sortable[P]) ScanText(v pgtype.Text) error {
return scanText(s, v)
}
func (s Sortable[P]) UUIDValue() (pgtype.UUID, error) {
return uuidValue(s)
}
func (s *Sortable[P]) ScanUUID(v pgtype.UUID) error {
return scanUUID(s, v)
}