// Package ulid 实现 ULID(Universally Unique Lexicographically Sortable // Identifier)生成:48bit 毫秒时间戳 + 80bit CSPRNG 随机,Crockford Base32 // 编码为 26 字符。规范参考 github.com/ulid/spec,此处原生实现避免引入依赖。 // // 全项目对外 ID(tenant/license/activation)统一使用本包。 package ulid import ( "crypto/rand" "fmt" "sync" "time" ) const crockford = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" // entropyMu 串行化随机读取,降低同毫秒碰撞下的重试竞争(rand 本身线程安全)。 var entropyMu sync.Mutex // New 生成 26 字符 ULID。字典序即时间序。 func New() (string, error) { var b [16]byte ms := uint64(time.Now().UnixMilli()) // 48bit 时间戳大端序占 b[0:6](大端序字节拆分的有意截断) b[0] = byte(ms >> 40) //nolint:gosec // G115 b[1] = byte(ms >> 32) //nolint:gosec // G115 b[2] = byte(ms >> 24) //nolint:gosec // G115 b[3] = byte(ms >> 16) //nolint:gosec // G115 b[4] = byte(ms >> 8) //nolint:gosec // G115 b[5] = byte(ms) //nolint:gosec // G115 entropyMu.Lock() _, err := rand.Read(b[6:]) entropyMu.Unlock() if err != nil { return "", fmt.Errorf("ulid: %w", err) } return encode(b), nil } // encode 把 16 字节按 5bit 一组编码为 26 字符。 // 130bit 流 = 2 个前导零位 + 128bit 数据(数据右对齐,无尾部填充)。 func encode(b [16]byte) string { var out [26]byte const lead = 2 // 130 - 128 for i := range out { out[i] = crockford[extract(b, i*5-lead, 5)] } return string(out[:]) } // extract 从字节数组的 bitPos 位起取 n 位(MSB 优先,允许跨字节)。 // bitPos 为负时按前导零位处理。 func extract(b [16]byte, bitPos, n int) byte { var v byte for j := range n { p := bitPos + j v <<= 1 if p >= 0 { if byteIdx := p / 8; byteIdx < len(b) { v |= (b[byteIdx] >> (7 - p%8)) & 1 } } } return v }