// Package ids generates short, time-sortable identifiers. package ids import ( "crypto/rand" "time" ) // Crockford base32, lowercase. Safe inside Telegram callback data and URLs. const alphabet = "0123456789abcdefghjkmnpqrstvwxyz" // New returns a 26 character identifier: 10 characters of millisecond // timestamp followed by 16 random characters. Identifiers created later sort // after earlier ones, which keeps queue order stable. func New() string { return newAt(time.Now()) } func newAt(t time.Time) string { var out [26]byte ms := uint64(t.UnixMilli()) for i := 9; i >= 0; i-- { out[i] = alphabet[ms&31] ms >>= 5 } var rnd [16]byte if _, err := rand.Read(rnd[:]); err != nil { panic("ids: no entropy: " + err.Error()) } for i := 0; i < 16; i++ { out[10+i] = alphabet[rnd[i]&31] } return string(out[:]) } // Valid reports whether s has the shape of an identifier from New. func Valid(s string) bool { if len(s) != 26 { return false } for i := 0; i < len(s); i++ { c := s[i] ok := false for j := 0; j < len(alphabet); j++ { if alphabet[j] == c { ok = true break } } if !ok { return false } } return true }