forked from lithammer/shortuuid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortuuid.go
58 lines (47 loc) · 1.49 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
package shortuuid
import (
"strings"
"github.com/google/uuid"
)
// DefaultEncoder is the default encoder uses when generating new UUIDs, and is
// based on Base57.
var DefaultEncoder = &base57{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 strings.HasPrefix(strings.ToLower(name), "http://"):
u = uuid.NewSHA1(uuid.NameSpaceURL, []byte(name))
case strings.HasPrefix(strings.ToLower(name), "https://"):
u = uuid.NewSHA1(uuid.NameSpaceURL, []byte(name))
default:
u = uuid.NewSHA1(uuid.NameSpaceDNS, []byte(name))
}
return DefaultEncoder.Encode(u)
}
// NewWithAlphabet returns a new UUIDv4, encoded with base57 using the
// alternative alphabet abc.
func NewWithAlphabet(abc string) string {
enc := base57{newAlphabet(abc)}
return enc.Encode(uuid.New())
}
// WithAlphabet returns a new base57 enocder using the
// alternative alphabet abc.
func WithAlphabet(abc string) Encoder {
return base57{newAlphabet(abc)}
}