Sign in

Search issue titles and bodies, change requests and comments. Private repositories you cannot read are not included.

vole
Clone

Read only, no credentials:

https://rodent.software/git/vole.git

Write over SSH with a registered key:

git clone ssh://git@0.0.0.0:2222/vole.git

A free and open-source forge that lives in your Git repo.

Blame · core/id/id.go

Line attribution on main · 44 line(s)

31df8bae
Keenan Nemetz
17d ago
1 // Package id generates ULIDs: 26 characters of Crockford base32, the first 48
2 // bits a millisecond timestamp. They are client-generated so nothing has to be
3 // assigned server-side, and they sort by creation time.
4 package id
5
6 import (
7 "crypto/rand"
8 "regexp"
9 "time"
10 )
11
12 const alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
13
14 var re = regexp.MustCompile(`^[0-9A-HJKMNP-TV-Z]{26}$`)
15
16 // New returns a ULID for t.
17 func New(t time.Time) (string, error) {
18 var out [26]byte
19 ms := uint64(t.UnixMilli())
20 for i := 9; i >= 0; i-- {
21 out[i] = alphabet[ms&31]
22 ms >>= 5
23 }
24 b := make([]byte, 16)
25 if _, err := rand.Read(b); err != nil {
26 return "", err
27 }
28 var acc uint32
29 var bits uint
30 pos := 10
31 for _, x := range b {
32 acc = acc<<8 | uint32(x)
33 bits += 8
34 for bits >= 5 && pos < 26 {
35 bits -= 5
36 out[pos] = alphabet[(acc>>bits)&31]
37 pos++
38 }
39 }
40 return string(out[:]), nil
41 }
42
43 // Valid reports whether s is a well-formed ULID.
44 func Valid(s string) bool { return re.MatchString(s) }