-
-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathshortuuid.go
69 lines (57 loc) · 1.82 KB
/
shortuuid.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
package shortuuid
import (
"crypto/sha1"
"strings"
"unsafe"
"github.com/google/uuid"
)
// DefaultEncoder is the default encoder uses when generating new UUIDs, and is
// based on Base57.
var DefaultEncoder = &encoder{newAlphabet(DefaultAlphabet)}
// Encoder is an interface for encoding/decoding UUIDs to strings.
type Encoder interface {
Encode(uuid.UUID) string
Decode(string) (uuid.UUID, error)
}
// New returns a new UUIDv4, encoded with base57.
func New() string {
return DefaultEncoder.Encode(uuid.New())
}
// NewWithEncoder returns a new UUIDv4, encoded with enc.
func NewWithEncoder(enc Encoder) string {
return enc.Encode(uuid.New())
}
// NewWithNamespace returns a new UUIDv5 (or v4 if name is empty), encoded with base57.
func NewWithNamespace(name string) string {
var u uuid.UUID
switch {
case name == "":
u = uuid.New()
case hasPrefixCaseInsensitive(name, "https://"):
u = hashedUUID(uuid.NameSpaceURL, name)
case hasPrefixCaseInsensitive(name, "http://"):
u = hashedUUID(uuid.NameSpaceURL, name)
default:
u = hashedUUID(uuid.NameSpaceDNS, name)
}
return DefaultEncoder.Encode(u)
}
// NewWithAlphabet returns a new UUIDv4, encoded with base57 using the
// alternative alphabet abc.
func NewWithAlphabet(abc string) string {
enc := encoder{newAlphabet(abc)}
return enc.Encode(uuid.New())
}
func hasPrefixCaseInsensitive(s, prefix string) bool {
return len(s) >= len(prefix) && strings.EqualFold(s[:len(prefix)], prefix)
}
func hashedUUID(space uuid.UUID, data string) (u uuid.UUID) {
h := sha1.New()
h.Write(space[:]) //nolint:errcheck
h.Write(unsafe.Slice(unsafe.StringData(data), len(data))) //nolint:errcheck
s := h.Sum(make([]byte, 0, sha1.Size))
copy(u[:], s)
u[6] = (u[6] & 0x0f) | uint8((5&0xf)<<4)
u[8] = (u[8] & 0x3f) | 0x80 // RFC 4122 variant
return u
}