github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/snow/baseothers.go (about) 1 package snow 2 3 import ( 4 "encoding/base64" 5 "encoding/binary" 6 "strconv" 7 ) 8 9 // Base64 returns a base64 string of the snowflake ID 10 func (f ID) Base64() string { return base64.StdEncoding.EncodeToString(f.Bytes()) } 11 12 // ParseBase64 converts a base64 string into a snowflake ID 13 func ParseBase64(id string) (ID, error) { 14 b, err := base64.StdEncoding.DecodeString(id) 15 if err != nil { 16 return -1, err 17 } 18 19 return ParseBytes(b) 20 } 21 22 // Base2 returns a string base2 of the snowflake ID 23 func (f ID) Base2() string { return strconv.FormatInt(int64(f), 2) } 24 25 // ParseBase2 converts a Base2 string into a snowflake ID 26 func ParseBase2(id string) (ID, error) { 27 i, err := strconv.ParseInt(id, 2, 64) 28 return ID(i), err 29 } 30 31 // Base36 returns a base36 string of the snowflake ID 32 func (f ID) Base36() string { return strconv.FormatInt(int64(f), 36) } 33 34 // ParseBase36 converts a Base36 string into a snowflake ID 35 func ParseBase36(id string) (ID, error) { 36 i, err := strconv.ParseInt(id, 36, 64) 37 return ID(i), err 38 } 39 40 // Int32 returns an int32 of the snowflake ID 41 func (f ID) Int32() int32 { return int32(f) } 42 43 // Uint32 returns an uint32 of the snowflake ID 44 func (f ID) Uint32() uint32 { return uint32(f) } 45 46 // Int64 returns an int64 of the snowflake ID 47 func (f ID) Int64() int64 { return int64(f) } 48 49 // Uint64 returns an uint64 of the snowflake ID 50 func (f ID) Uint64() uint64 { return uint64(f) } 51 52 // ParseInt64 converts an int64 into a snowflake ID 53 func ParseInt64(id int64) ID { return ID(id) } 54 55 // String returns a string of the snowflake ID 56 func (f ID) String() string { return strconv.FormatInt(int64(f), 10) } 57 58 // ParseString converts a string into a snowflake ID 59 func ParseString(id string) (ID, error) { 60 i, err := strconv.ParseInt(id, 10, 64) 61 return ID(i), err 62 } 63 64 // Bytes returns a byte slice of the snowflake ID 65 func (f ID) Bytes() []byte { return []byte(f.String()) } 66 67 // ParseBytes converts a byte slice into a snowflake ID 68 func ParseBytes(id []byte) (ID, error) { 69 i, err := strconv.ParseInt(string(id), 10, 64) 70 return ID(i), err 71 } 72 73 // IntBytes returns an array of bytes of the snowflake ID, encoded as a 74 // big endian integer. 75 func (f ID) IntBytes() [8]byte { 76 var b [8]byte 77 78 binary.BigEndian.PutUint64(b[:], uint64(f)) 79 80 return b 81 } 82 83 // ParseIntBytes converts an array of bytes encoded as big endian integer as 84 // a snowflake ID 85 func ParseIntBytes(id [8]byte) ID { 86 return ID(binary.BigEndian.Uint64(id[:])) 87 }