Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
30ddec3409 | ||
|
|
357b19d9ad | ||
|
|
53330ceab9 | ||
|
|
7ff09285dd | ||
|
|
39e8723dbd | ||
|
|
9952b2677c | ||
|
|
fbc419f92e | ||
|
|
0d486f5d01 | ||
|
|
66ccb82415 |
30
README.md
30
README.md
@@ -22,25 +22,31 @@ Golang 中可以使用的常用辅助功能工具箱。主要配备以下功能
|
||||
- [x] KeyPair 生成器
|
||||
- [x] Key 导入与导出
|
||||
- [x] RSA 签名算法
|
||||
- 散列及校验和算法。
|
||||
- [x] Sha512 散列算法
|
||||
- [x] Sha256 散列算法
|
||||
- [x] Sha1 散列算法
|
||||
- [x] MD5 散列算法
|
||||
- [x] CRC8 校验和算法
|
||||
- [x] CRC16 校验和算法
|
||||
- [x] CRC32 校验和算法
|
||||
- [x] CRC64 校验和算法
|
||||
- [x] pHash 图像感知算法
|
||||
- 散列及校验和算法
|
||||
- [x] Sha512 散列算法(便捷封装)
|
||||
- [x] Sha256 散列算法(便捷封装)
|
||||
- [x] Sha1 散列算法(便捷封装)
|
||||
- [x] MD5 散列算法(便捷封装)
|
||||
- [x] CRC8 校验和算法(便捷封装)
|
||||
- [x] CRC16 校验和算法(便捷封装)
|
||||
- [x] CRC32 校验和算法(便捷封装)
|
||||
- [x] CRC64 校验和算法(便捷封装)
|
||||
- [x] pHash 图像感知算法(便捷封装)
|
||||
- [x] BLAKE2b 校验和算法(便捷封装)
|
||||
- [x] BLAKE3 校验和算法(便捷封装)
|
||||
- [ ] BlockHash 散列算法
|
||||
- 唯一序列号生成器
|
||||
- [x] 冰雹 ID 生成器(短主机精简日期版雪花 ID)
|
||||
- [x] UUID 生成器
|
||||
- [x] 冰雹 ID 生成器(短主机精简日期版雪花 ID)
|
||||
- [x] UUIDv4 生成器
|
||||
- [x] UUIDv7 生成器(自定义时间戳分布式版本)
|
||||
- [x] UUIDv7 比较及排序
|
||||
- [x] 基于 Base36 的 short UUIDv7 转换器
|
||||
- [x] short UUID 生成器
|
||||
- 验证码生成器
|
||||
- [x] 随机验证码生成算法
|
||||
- 序列化算法
|
||||
- [x] Base64 算法
|
||||
- [x] Base36 算法
|
||||
- [x] Hex 直转
|
||||
- 常用工具函数
|
||||
- [ ] 日期时间函数
|
||||
|
||||
6
go.mod
6
go.mod
@@ -1,13 +1,15 @@
|
||||
module archgrid.xyz/ag/toolsbox
|
||||
|
||||
go 1.20
|
||||
go 1.24.0
|
||||
|
||||
require go.uber.org/zap v1.24.0
|
||||
|
||||
require (
|
||||
github.com/azr/gift v1.1.2 // indirect
|
||||
github.com/disintegration/imaging v1.6.2 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.0.9 // indirect
|
||||
golang.org/x/image v0.0.0-20220722155232-062f8c9fd539 // indirect
|
||||
golang.org/x/sys v0.36.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -17,4 +19,6 @@ require (
|
||||
github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f
|
||||
go.uber.org/atomic v1.7.0 // indirect
|
||||
go.uber.org/multierr v1.6.0 // indirect
|
||||
golang.org/x/crypto v0.42.0
|
||||
lukechampine.com/blake3 v1.4.1
|
||||
)
|
||||
|
||||
8
go.sum
8
go.sum
@@ -10,6 +10,8 @@ github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/howeyc/crc16 v0.0.0-20171223171357-2b2a61e366a6 h1:IIVxLyDUYErC950b8kecjoqDet8P5S4lcVRUOM6rdkU=
|
||||
github.com/howeyc/crc16 v0.0.0-20171223171357-2b2a61e366a6/go.mod h1:JslaLRrzGsOKJgFEPBP65Whn+rdwDQSk0I0MCRFe2Zw=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f h1:1R9KdKjCNSd7F8iGTxIpoID9prlYH8nuNYKt0XvweHA=
|
||||
github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f/go.mod h1:vQhwQ4meQEDfahT5kd61wLAF5AAeh5ZPLVI4JJ/tYo8=
|
||||
@@ -21,9 +23,15 @@ go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4=
|
||||
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
|
||||
go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
|
||||
go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg=
|
||||
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
||||
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/image v0.0.0-20220722155232-062f8c9fd539 h1:/eM0PCrQI2xd471rI+snWuu251/+/jpBpZqir2mPdnU=
|
||||
golang.org/x/image v0.0.0-20220722155232-062f8c9fd539/go.mod h1:doUCurBvlfPMKfmIpRIywoHmhN3VyhnoFDbvIEWF4hY=
|
||||
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
|
||||
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg=
|
||||
lukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=
|
||||
|
||||
117
hash/blake2b/blake2b.go
Normal file
117
hash/blake2b/blake2b.go
Normal file
@@ -0,0 +1,117 @@
|
||||
// 提供Blake2B系列散列算法函数和校验和函数。
|
||||
package blake2b
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"golang.org/x/crypto/blake2b"
|
||||
)
|
||||
|
||||
// 根据给定的位数返回一个散列算法的Hash实例。
|
||||
func hasherSelect(bitSize int) hash.Hash {
|
||||
switch bitSize {
|
||||
case 224:
|
||||
hasher, _ := blake2b.New256(nil)
|
||||
return hasher
|
||||
case 256:
|
||||
hasher, _ := blake2b.New256(nil)
|
||||
return hasher
|
||||
case 384:
|
||||
hasher, _ := blake2b.New384(nil)
|
||||
return hasher
|
||||
case 512:
|
||||
hasher, _ := blake2b.New512(nil)
|
||||
return hasher
|
||||
default:
|
||||
hasher, _ := blake2b.New256(nil)
|
||||
return hasher
|
||||
}
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake2B校验和,返回字节数组。
|
||||
func Blake2b(data []byte) []byte {
|
||||
hasher := hasherSelect(512)
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake2B/256校验和,返回字节数组。
|
||||
func Blake2b_256(data []byte) []byte {
|
||||
hasher := hasherSelect(256)
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake2B/384校验和,返回字节数组。
|
||||
func Blake2b_384(data []byte) []byte {
|
||||
hasher := hasherSelect(384)
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake2B/224校验和,返回字节数组。
|
||||
func Blake2b_224(data []byte) []byte {
|
||||
hasher := hasherSelect(224)
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake2B校验和,返回十六进制字符串。
|
||||
func Blake2bHex(data []byte) string {
|
||||
return hex.EncodeToString(Blake2b(data))
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake2B/256校验和,返回十六进制字符串。
|
||||
func Blake2b_256Hex(data []byte) string {
|
||||
return hex.EncodeToString(Blake2b_256(data))
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake2B/384校验和,返回十六进制字符串。
|
||||
func Blake2b_384Hex(data []byte) string {
|
||||
return hex.EncodeToString(Blake2b_384(data))
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake2B/224校验和,返回十六进制字符串。
|
||||
func Blake2b_224Hex(data []byte) string {
|
||||
return hex.EncodeToString(Blake2b_224(data))
|
||||
}
|
||||
|
||||
// 根据给定位数计算一个字节数组的Blake2B校验和,返回字节数组。
|
||||
func Sum(data []byte, bitSize ...int) []byte {
|
||||
hasher := hasherSelect(append(bitSize, 512)[0])
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 根据给定位数计算一个字节数组的Blake2B校验和,返回十六进制字符串。
|
||||
func SumHex(data []byte, bitSize ...int) string {
|
||||
return hex.EncodeToString(Sum(data, bitSize...))
|
||||
}
|
||||
|
||||
// 根据给定位数计算一个文件的Blake2B校验和,返回字节数组。
|
||||
func SumFile(file string, bitSize ...int) ([]byte, error) {
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("未能打开指定文件,%w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
hasher := hasherSelect(append(bitSize, 512)[0])
|
||||
if _, err := io.Copy(hasher, f); err != nil {
|
||||
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
|
||||
}
|
||||
return hasher.Sum(nil), nil
|
||||
}
|
||||
|
||||
// 根据给定位数计算一个文件的Blake2B校验和,返回十六进制字符串。
|
||||
func SumFileHex(file string, bitSize ...int) (string, error) {
|
||||
hash, err := SumFile(file, bitSize...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(hash), nil
|
||||
}
|
||||
112
hash/blake3/blake3.go
Normal file
112
hash/blake3/blake3.go
Normal file
@@ -0,0 +1,112 @@
|
||||
// 提供Blake3系列散列算法函数和校验和函数。
|
||||
package blake3
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"lukechampine.com/blake3"
|
||||
)
|
||||
|
||||
// 根据给定的位数返回一个散列算法的Hash实例。
|
||||
func hasherSelect(bitSize int) hash.Hash {
|
||||
switch bitSize {
|
||||
case 224:
|
||||
return blake3.New(28, nil)
|
||||
case 256:
|
||||
return blake3.New(32, nil)
|
||||
case 384:
|
||||
return blake3.New(48, nil)
|
||||
case 512:
|
||||
return blake3.New(64, nil)
|
||||
default:
|
||||
return blake3.New(32, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake3校验和,返回字节数组。
|
||||
func Blake3(data []byte) []byte {
|
||||
hasher := hasherSelect(512)
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake3/256校验和,返回字节数组。
|
||||
func Blake3_256(data []byte) []byte {
|
||||
hasher := hasherSelect(256)
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake3/384校验和,返回字节数组。
|
||||
func Blake3_384(data []byte) []byte {
|
||||
hasher := hasherSelect(384)
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake3/224校验和,返回字节数组。
|
||||
func Blake3_224(data []byte) []byte {
|
||||
hasher := hasherSelect(224)
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake3校验和,返回十六进制字符串。
|
||||
func Blake3Hex(data []byte) string {
|
||||
return hex.EncodeToString(Blake3(data))
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake3/256校验和,返回十六进制字符串。
|
||||
func Blake3_256Hex(data []byte) string {
|
||||
return hex.EncodeToString(Blake3_256(data))
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake3/384校验和,返回十六进制字符串。
|
||||
func Blake3_384Hex(data []byte) string {
|
||||
return hex.EncodeToString(Blake3_384(data))
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Blake3/224校验和,返回十六进制字符串。
|
||||
func Blake3_224Hex(data []byte) string {
|
||||
return hex.EncodeToString(Blake3_224(data))
|
||||
}
|
||||
|
||||
// 根据给定位数计算一个字节数组的Blake3校验和,返回字节数组。
|
||||
func Sum(data []byte, bitSize ...int) []byte {
|
||||
hasher := hasherSelect(append(bitSize, 512)[0])
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 根据给定位数计算一个字节数组的Blake3校验和,返回十六进制字符串。
|
||||
func SumHex(data []byte, bitSize ...int) string {
|
||||
return hex.EncodeToString(Sum(data, bitSize...))
|
||||
}
|
||||
|
||||
// 根据给定位数计算一个文件的Blake3校验和,返回字节数组。
|
||||
func SumFile(file string, bitSize ...int) ([]byte, error) {
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("未能打开指定文件,%w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
hasher := hasherSelect(append(bitSize, 512)[0])
|
||||
if _, err := io.Copy(hasher, f); err != nil {
|
||||
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
|
||||
}
|
||||
return hasher.Sum(nil), nil
|
||||
}
|
||||
|
||||
// 根据给定位数计算一个文件的Blake3校验和,返回十六进制字符串。
|
||||
func SumFileHex(file string, bitSize ...int) (string, error) {
|
||||
hash, err := SumFile(file, bitSize...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(hash), nil
|
||||
}
|
||||
13
serial_code/uuidv7/errors.go
Normal file
13
serial_code/uuidv7/errors.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package uuidv7
|
||||
|
||||
type UUIDv7GeneratorNotInitializedError struct{}
|
||||
|
||||
func (e *UUIDv7GeneratorNotInitializedError) Error() string {
|
||||
return "UUIDv7生成器尚未初始化"
|
||||
}
|
||||
|
||||
type UUIDv7NodeIDExceededError struct{}
|
||||
|
||||
func (e *UUIDv7NodeIDExceededError) Error() string {
|
||||
return "UUIDv7节点ID超出范围"
|
||||
}
|
||||
258
serial_code/uuidv7/uuid.go
Normal file
258
serial_code/uuidv7/uuid.go
Normal file
@@ -0,0 +1,258 @@
|
||||
package uuidv7
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"archgrid.xyz/ag/toolsbox/serialize/base36"
|
||||
"archgrid.xyz/ag/toolsbox/serialize/base64"
|
||||
)
|
||||
|
||||
const (
|
||||
epoch = 1645566142222 // 自定义纪元:2022-02-22 22:22:22.222 UTC
|
||||
nodeBits = 5 // 主机编号容量为0~32
|
||||
sequenceBits = 18 // 每毫秒生成序列号最大为2^18-1,即262144个
|
||||
maxNodeID = (1 << nodeBits) - 1
|
||||
maxSequence = (1 << sequenceBits) - 1
|
||||
timestampShift = nodeBits + sequenceBits
|
||||
nodeShift = sequenceBits
|
||||
)
|
||||
|
||||
type UUIDv7Generator struct {
|
||||
locker sync.Mutex
|
||||
nodeID int64
|
||||
lastTime int64
|
||||
sequence int64
|
||||
}
|
||||
|
||||
type UUIDv7Components struct {
|
||||
Timestamp int64 // 毫秒时间戳(相对于自定义纪元)
|
||||
NodeID int64 // 5位节点ID
|
||||
Sequence int64 // 18位序列号
|
||||
Version int // 版本号(应为7)
|
||||
Variant int // 变体(应为2,表示10xx)
|
||||
RawBytes [16]byte // 原始字节
|
||||
}
|
||||
|
||||
var generatorInstance *UUIDv7Generator
|
||||
|
||||
// 获取UUIDv7生成器实例。如果实例尚未初始化,则返回错误。
|
||||
func Generator() (*UUIDv7Generator, error) {
|
||||
if generatorInstance == nil {
|
||||
return nil, &UUIDv7GeneratorNotInitializedError{}
|
||||
}
|
||||
return generatorInstance, nil
|
||||
}
|
||||
|
||||
// 指定一个主机编号,并完成UUIDv7生成器的初始化。如果主机编号超出范围,则返回错误。
|
||||
func Initialize(hostSerial int64) error {
|
||||
if hostSerial < 0 || hostSerial > maxNodeID {
|
||||
return &UUIDv7NodeIDExceededError{}
|
||||
}
|
||||
generatorInstance = &UUIDv7Generator{
|
||||
nodeID: hostSerial,
|
||||
lastTime: epoch,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 获取当前时间对应的新纪元毫秒时间戳。
|
||||
func (g *UUIDv7Generator) Now() int64 {
|
||||
return time.Now().UnixMilli() - epoch
|
||||
}
|
||||
|
||||
// 按顺序生成一个UUIDv7序号组件。
|
||||
func (g *UUIDv7Generator) Next() UUIDv7Components {
|
||||
g.locker.Lock()
|
||||
defer g.locker.Unlock()
|
||||
now := g.Now()
|
||||
if now < g.lastTime {
|
||||
// 防止时间回拔的情况,发生回拔时,直接使用上一次的时间戳
|
||||
now = g.lastTime
|
||||
}
|
||||
if now == g.lastTime {
|
||||
g.sequence++
|
||||
if g.sequence > maxSequence {
|
||||
time.Sleep(time.Millisecond)
|
||||
now = g.Now()
|
||||
g.sequence = 0
|
||||
}
|
||||
} else {
|
||||
g.sequence = 0
|
||||
}
|
||||
g.lastTime = now
|
||||
return UUIDv7Components{
|
||||
Timestamp: now,
|
||||
NodeID: g.nodeID,
|
||||
Sequence: g.sequence,
|
||||
Version: 7,
|
||||
Variant: 2,
|
||||
}
|
||||
}
|
||||
|
||||
// 读取随机字节
|
||||
func (c *UUIDv7Components) readRandom(bytes []byte) error {
|
||||
_, err := rand.Read(bytes)
|
||||
return err
|
||||
}
|
||||
|
||||
// 获取UUIDv7原始字节数组
|
||||
func (c *UUIDv7Components) Bytes() [16]byte {
|
||||
// 构造 UUID
|
||||
var uuid [16]byte
|
||||
// 时间戳(48 位)
|
||||
timestamp := uint64(c.Timestamp) << timestampShift
|
||||
seqAndNode := (uint64(c.Sequence) << nodeShift) | uint64(c.NodeID)
|
||||
// 写入高位时间戳
|
||||
uuid[0] = byte(timestamp >> 56)
|
||||
uuid[1] = byte(timestamp >> 48)
|
||||
uuid[2] = byte(timestamp >> 40)
|
||||
uuid[3] = byte(timestamp >> 32)
|
||||
uuid[4] = byte(timestamp >> 24)
|
||||
uuid[5] = byte(timestamp >> 16)
|
||||
// 写入低位时间戳 + 版本号(4 位)
|
||||
uuid[6] = byte((timestamp >> 8) | 0x70) // version 7
|
||||
uuid[7] = byte(timestamp)
|
||||
// 写入 seq + node
|
||||
uuid[8] = byte((seqAndNode >> 16) | 0x80) // variant 10xx
|
||||
uuid[9] = byte(seqAndNode >> 8)
|
||||
uuid[10] = byte(seqAndNode)
|
||||
// 剩余位全为 0(可扩展为更多节点 ID 或随机数)
|
||||
randomBytes := make([]byte, 5)
|
||||
if err := c.readRandom(randomBytes); err != nil {
|
||||
// 如果随机数生成失败,使用时间相关值作为后备
|
||||
t := time.Now().UnixNano()
|
||||
randomBytes[0] = byte(t)
|
||||
randomBytes[1] = byte(t >> 8)
|
||||
randomBytes[2] = byte(t >> 16)
|
||||
randomBytes[3] = byte(t >> 24)
|
||||
randomBytes[4] = byte(c.Sequence)
|
||||
}
|
||||
copy(uuid[11:16], randomBytes)
|
||||
return uuid
|
||||
}
|
||||
|
||||
// 获取UUIDv7字符串
|
||||
func (c *UUIDv7Components) String() string {
|
||||
uuid := c.Bytes()
|
||||
return fmt.Sprintf("%x-%x-%x-%x-%x",
|
||||
uuid[0:4],
|
||||
uuid[4:6],
|
||||
uuid[6:8],
|
||||
uuid[8:10],
|
||||
uuid[10:16])
|
||||
}
|
||||
|
||||
// 获取UUIDv7的Base64格式字符串
|
||||
func (c *UUIDv7Components) ToBase64() string {
|
||||
uuid := c.Bytes()
|
||||
return base64.ToBase64(uuid[:])
|
||||
}
|
||||
|
||||
// 获取UUIDv7的Base36格式字符串
|
||||
func (c *UUIDv7Components) ToBase36() string {
|
||||
uuid := c.Bytes()
|
||||
return base36.Encode(uuid[:])
|
||||
}
|
||||
|
||||
// 与另一个UUIDv7进行比较,按照时间戳、序列号、节点ID进行排序
|
||||
func (c *UUIDv7Components) Compare(b *UUIDv7Components) int {
|
||||
if c.Timestamp > b.Timestamp {
|
||||
return 1
|
||||
}
|
||||
if c.Timestamp < b.Timestamp {
|
||||
return -1
|
||||
}
|
||||
|
||||
if c.Sequence > b.Sequence {
|
||||
return 1
|
||||
}
|
||||
if c.Sequence < b.Sequence {
|
||||
return -1
|
||||
}
|
||||
|
||||
if c.NodeID > b.NodeID {
|
||||
return -1
|
||||
}
|
||||
if c.NodeID < b.NodeID {
|
||||
return 1
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
// 对解析后的UUIDv7进行比较,按照时间戳、序列号、节点ID进行排序
|
||||
func CompareUUIDv7(a, b *UUIDv7Components) int {
|
||||
return a.Compare(b)
|
||||
}
|
||||
|
||||
// 从字节数组解析 UUIDv7
|
||||
func ParseUUIDv7FromBytes(data [16]byte) (*UUIDv7Components, error) {
|
||||
// 提取时间戳(前48位)
|
||||
timestamp := (int64(data[0]) << 40) |
|
||||
(int64(data[1]) << 32) |
|
||||
(int64(data[2]) << 24) |
|
||||
(int64(data[3]) << 16) |
|
||||
(int64(data[4]) << 8) |
|
||||
int64(data[5])
|
||||
// 提取版本号(第6字节的高4位)
|
||||
version := int(data[6] >> 4)
|
||||
// 提取变体(第8字节的高2位)
|
||||
variant := int(data[8] >> 6)
|
||||
// 提取序列号和节点ID
|
||||
// 第8字节的低2位 + 第9字节 + 第10字节的高3位组成23位
|
||||
seqAndNode := (int64(data[8]&0x3F) << 16) | // 第8字节低6位
|
||||
(int64(data[9]) << 8) | // 第9字节
|
||||
int64(data[10]) // 第10字节
|
||||
// 分离序列号(高18位)和节点ID(低5位)
|
||||
sequence := seqAndNode >> 5
|
||||
nodeID := seqAndNode & 0x1F
|
||||
return &UUIDv7Components{
|
||||
Timestamp: timestamp,
|
||||
NodeID: nodeID,
|
||||
Sequence: sequence,
|
||||
Version: version,
|
||||
Variant: variant,
|
||||
RawBytes: data,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 从字符串解析 UUIDv7
|
||||
func ParseUUIDv7FromString(uuidStr string) (*UUIDv7Components, error) {
|
||||
// 移除连字符并验证长度
|
||||
cleanStr := strings.ReplaceAll(uuidStr, "-", "")
|
||||
if len(cleanStr) != 32 {
|
||||
return nil, fmt.Errorf("无效的UUIDv7字符串长度")
|
||||
}
|
||||
// 解码十六进制字符串
|
||||
bytes, err := hex.DecodeString(cleanStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("无效的UUIDv7字符串格式: %v", err)
|
||||
}
|
||||
// 转换为数组
|
||||
var uuidBytes [16]byte
|
||||
copy(uuidBytes[:], bytes)
|
||||
return ParseUUIDv7FromBytes(uuidBytes)
|
||||
}
|
||||
|
||||
// 从Base64格式字符串解析 UUIDv7
|
||||
func ParseUUIDv7FromBase64(base64Str string) (*UUIDv7Components, error) {
|
||||
bytes, err := base64.FromBase64(base64Str)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("无效的Base64格式字符串: %v", err)
|
||||
}
|
||||
return ParseUUIDv7FromBytes([16]byte(bytes))
|
||||
}
|
||||
|
||||
// 从Base36格式字符串解析 UUIDv7
|
||||
func ParseUUIDv7FromBase36(base36Str string) (*UUIDv7Components, error) {
|
||||
bytes, err := base36.Decode(base36Str)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("无效的Base36格式字符串: %v", err)
|
||||
}
|
||||
return ParseUUIDv7FromBytes([16]byte(bytes))
|
||||
}
|
||||
108
serialize/base36/base36.go
Normal file
108
serialize/base36/base36.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package base36
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Encode 将字节数据编码为Base36字符串(大写),使用=作为padding字符
|
||||
func Encode(src []byte) string {
|
||||
if len(src) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
// 将字节转换为big.Int
|
||||
num := new(big.Int).SetBytes(src)
|
||||
|
||||
// 如果输入为全零字节,则直接返回"0"
|
||||
if num.Cmp(big.NewInt(0)) == 0 {
|
||||
return "0"
|
||||
}
|
||||
|
||||
// 进行Base36编码
|
||||
var result strings.Builder
|
||||
base := big.NewInt(36)
|
||||
zero := big.NewInt(0)
|
||||
remainder := new(big.Int)
|
||||
|
||||
// 重复除以36,获取余数作为字符
|
||||
for num.Cmp(zero) > 0 {
|
||||
num.DivMod(num, base, remainder)
|
||||
digit := remainder.Int64()
|
||||
|
||||
if digit < 10 {
|
||||
result.WriteString(fmt.Sprintf("%d", digit))
|
||||
} else {
|
||||
result.WriteString(fmt.Sprintf("%c", 'A'+digit-10))
|
||||
}
|
||||
}
|
||||
|
||||
// 反转字符串,因为我们是从低位开始计算的
|
||||
encoded := result.String()
|
||||
runes := []rune(encoded)
|
||||
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
|
||||
runes[i], runes[j] = runes[j], runes[i]
|
||||
}
|
||||
|
||||
return string(runes)
|
||||
}
|
||||
|
||||
// Decode 将Base36字符串(可为任意大小写)解码为字节数组
|
||||
func Decode(src string) ([]byte, error) {
|
||||
if src == "" {
|
||||
return []byte{}, nil
|
||||
}
|
||||
|
||||
// 移除padding字符
|
||||
src = strings.ReplaceAll(src, "=", "")
|
||||
src = strings.ToUpper(src)
|
||||
|
||||
// 使用big.Int进行解码
|
||||
num := big.NewInt(0)
|
||||
base := big.NewInt(36)
|
||||
|
||||
for _, char := range src {
|
||||
var digit int64
|
||||
|
||||
switch {
|
||||
case char >= '0' && char <= '9':
|
||||
digit = int64(char - '0')
|
||||
case char >= 'A' && char <= 'Z':
|
||||
digit = int64(char - 'A' + 10)
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid character %c in base36 string", char)
|
||||
}
|
||||
|
||||
num.Mul(num, base)
|
||||
num.Add(num, big.NewInt(digit))
|
||||
}
|
||||
|
||||
// 转换为字节数组
|
||||
return num.Bytes(), nil
|
||||
}
|
||||
|
||||
// EncodeToString 是Encode的别名,用于保持与标准库一致的命名
|
||||
func EncodeToString(src []byte) string {
|
||||
return Encode(src)
|
||||
}
|
||||
|
||||
// DecodeString 是Decode的别名,用于保持与标准库一致的命名
|
||||
func DecodeString(src string) ([]byte, error) {
|
||||
return Decode(src)
|
||||
}
|
||||
|
||||
// EncodeInt64 将int64转换为Base36字符串
|
||||
func EncodeInt64(num int64) string {
|
||||
return EncodeToString(big.NewInt(num).Bytes())
|
||||
}
|
||||
|
||||
// DecodeToInt64 将Base36字符串解码为int64
|
||||
func DecodeToInt64(src string) (int64, error) {
|
||||
bytes, err := DecodeString(src)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return new(big.Int).SetBytes(bytes).Int64(), nil
|
||||
}
|
||||
42
serialize/base36/base36_test.go
Normal file
42
serialize/base36/base36_test.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package base36
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func FuzzEncode(f *testing.F) {
|
||||
testCases := []string{"a", "abc", "uuid"}
|
||||
for _, tc := range testCases {
|
||||
f.Add(tc)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, a string) {
|
||||
encoded := Encode([]byte(a))
|
||||
redecoded, err := Decode(encoded)
|
||||
fmt.Printf("Origin: %s, Encoded: %s\n", a, encoded)
|
||||
if err != nil {
|
||||
t.Errorf("Decode(%q) failed: %v", encoded, err)
|
||||
}
|
||||
if string(redecoded) != a {
|
||||
t.Errorf("Decode(%q) = %q, want %q", encoded, redecoded, a)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzEncodeInt64(f *testing.F) {
|
||||
testCases := []int64{1, 6, 34598347534, 234532543, 2342546456, 34587639284756293}
|
||||
for _, tc := range testCases {
|
||||
f.Add(tc)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, a int64) {
|
||||
encoded := EncodeInt64(a)
|
||||
redecoded, err := DecodeToInt64(encoded)
|
||||
fmt.Printf("Origin: %d, Encoded: %s\n", a, encoded)
|
||||
if err != nil {
|
||||
t.Errorf("Decode(%q) failed: %v", encoded, err)
|
||||
}
|
||||
if redecoded != a {
|
||||
t.Errorf("Decode(%q) = %q, want %q", encoded, redecoded, a)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user