// Package snowflake provides utility functions for generating unique identifiers // (Snowflake IDs) based on a custom implementation inspired by the Snowflake algorithm (https://pkg.go.dev/github.com/godruoyi/go-snowflake#section-sourcefiles). // The Snowflake IDs generated by this package ensure uniqueness and are suitable for // distributed systems. The package offers a mechanism to convert these IDs // to standard SnowflakeID format strings, making them compatible with systems // requiring UUIDs. // Add import "gno.land/p/demo/entropy" to use the entropy package. For of the pseudo-random number generator. // TimestampLength is 42-bit. // 42 it's the maximum value that can be returned "2^42", It's represent 139 years (2^42 secondes) // SequenBits allows for 4096 unique IDs to be generated per millisecond. package snowflake import ( "chain/runtime" "encoding/binary" "encoding/hex" "time" "gno.land/p/demo/entropy" "gno.land/p/nt/ufmt/v0" ) const ( TimestampBits uint8 = 42 MachineIDBits uint64 = 10 SequenceBits uint64 = 12 MaxSequence uint16 = 1<> 60) bytes[1] = byte(id >> 52) bytes[2] = byte(id >> 44) bytes[3] = byte(id >> 36) bytes[4] = byte(id >> 28) bytes[5] = byte(id >> 20) bytes[6] = byte(id >> 12) bytes[7] = byte(id >> 4) // set the version and variant bits according to SnowflakeID specification. bytes[6] = (bytes[6] & 0x0f) | 0x40 // version 4 (random) bytes[8] = (bytes[8] & 0x3f) | 0x80 // variant 1 (RFC 4122) hexStr := hex.EncodeToString(bytes) return ufmt.Sprintf("%s-%s-%s-%s-%s", hexStr[0:8], hexStr[8:12], hexStr[12:16], hexStr[16:20], hexStr[20:], ) } func uint64ToBytes(i uint64) []byte { buf := make([]byte, 8) binary.BigEndian.PutUint64(buf, i) return buf }