mirror of
https://github.com/navidrome/navidrome.git
synced 2026-08-01 07:21:17 +00:00
feat(model): generate random ids as canonical 128-bit base62 values
This commit is contained in:
parent
c2c67e35eb
commit
38eb7c4b78
@ -2,20 +2,16 @@ package id
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/utils/nanoid"
|
||||
)
|
||||
|
||||
func NewRandom() string {
|
||||
id, err := nanoid.Generate("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 22)
|
||||
if err != nil {
|
||||
log.Error("Could not generate new ID", err)
|
||||
}
|
||||
return id
|
||||
var b [16]byte
|
||||
_, _ = rand.Read(b[:]) // never fails since Go 1.24
|
||||
return Encode128(b[:])
|
||||
}
|
||||
|
||||
// Encode128 renders a 16-byte value as the canonical 22-char zero-padded base62 id.
|
||||
|
||||
@ -34,6 +34,20 @@ var _ = Describe("Encode128/Decode128", func() {
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("NewRandom", func() {
|
||||
It("emits 22-char canonical ids that always fit 128 bits", func() {
|
||||
seen := make(map[string]struct{})
|
||||
for range 1000 {
|
||||
s := id.NewRandom()
|
||||
Expect(s).To(HaveLen(22))
|
||||
_, err := id.Decode128(s)
|
||||
Expect(err).ToNot(HaveOccurred(), "id %q must decode to 128 bits", s)
|
||||
seen[s] = struct{}{}
|
||||
}
|
||||
Expect(seen).To(HaveLen(1000))
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("NewHash", func() {
|
||||
It("keeps its historical output byte-for-byte (golden)", func() {
|
||||
Expect(id.NewHash("test")).To(Equal("5cLJPkLA5DK2BADhoeotPk"))
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user