-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsubtype.go
60 lines (50 loc) · 1.31 KB
/
subtype.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
package typeid
// Subtype is an interface used to create a more specific subtype of TypeID
// For example, if you want to create an `OrgID` type that only accepts
// an `org_` prefix.
type Subtype interface {
Prefix() string
Suffix() string
String() string
UUIDBytes() []byte
UUID() string
isTypeID() bool
}
var _ Subtype = (*TypeID[AnyPrefix])(nil)
type SubtypePtr[T any] interface {
*T
init(prefix string, suffix string)
}
func (tid *TypeID[P]) init(prefix string, suffix string) {
// In general TypeID is an immutable value-type, and pretty much every
// "mutation" should return a copy with the modifications instead of modifying
// the original. We make an exception for this *private* method, because
// sometimes we need to modify the fields in the process of initializing
// a new subtype.
// Only store the prefix if dealing with a subtype:
if isAnyPrefix[P]() {
tid.prefix = prefix
}
// If we're dealing with the "zero" suffix, we don't need to store it.
if suffix != zeroSuffix {
tid.suffix = suffix
}
}
func (tid TypeID[P]) isTypeID() bool {
return true
}
func isAnyID[T Subtype]() bool {
var id T
switch any(id).(type) {
case TypeID[AnyPrefix]:
return true
case AnyID:
return true
default:
return false
}
}
func defaultType[T Subtype]() string {
var id T
return id.Prefix()
}