feat(uuidv7): 完善 UUIDv7 功能并更新文档

- 实现 UUIDv7 生成、比较及排序功能
- 新增基于 Base36 和 Base64 的 UUIDv7 编码与解码方法
- 更新 README.md,标记相关功能为已完成状态
This commit is contained in:
徐涛
2025-10-06 09:27:30 +08:00
parent 39e8723dbd
commit 7ff09285dd
2 changed files with 49 additions and 16 deletions

View File

@@ -7,6 +7,9 @@ import (
"strings"
"sync"
"time"
"archgrid.xyz/ag/toolsbox/serialize/base36"
"archgrid.xyz/ag/toolsbox/serialize/base64"
)
const (
@@ -144,38 +147,50 @@ func (c *UUIDv7Components) String() string {
uuid[10:16])
}
// 对解析后的UUIDv7进行比较按照时间戳、序列号、节点ID进行排序
func CompareUUIDv7(a, b *UUIDv7Components) int {
if a.Timestamp > b.Timestamp {
// 获取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 a.Timestamp < b.Timestamp {
if c.Timestamp < b.Timestamp {
return -1
}
if a.Sequence > b.Sequence {
if c.Sequence > b.Sequence {
return 1
}
if a.Sequence < b.Sequence {
if c.Sequence < b.Sequence {
return -1
}
if a.NodeID > b.NodeID {
if c.NodeID > b.NodeID {
return -1
}
if a.NodeID < b.NodeID {
if c.NodeID < b.NodeID {
return 1
}
return 0
}
// 与另一个UUIDv7进行比较按照时间戳、序列号、节点ID进行排序
func (c *UUIDv7Components) Compare(b *UUIDv7Components) int {
return CompareUUIDv7(c, b)
// 对解析后的UUIDv7进行比较按照时间戳、序列号、节点ID进行排序
func CompareUUIDv7(a, b *UUIDv7Components) int {
return a.Compare(b)
}
// ParseUUIDv7FromBytes 从字节数组解析 UUIDv7
// 从字节数组解析 UUIDv7
func ParseUUIDv7FromBytes(data [16]byte) (*UUIDv7Components, error) {
// 提取时间戳前48位
timestamp := (int64(data[0]) << 40) |
@@ -206,7 +221,7 @@ func ParseUUIDv7FromBytes(data [16]byte) (*UUIDv7Components, error) {
}, nil
}
// ParseUUIDv7FromString 从字符串解析 UUIDv7
// 从字符串解析 UUIDv7
func ParseUUIDv7FromString(uuidStr string) (*UUIDv7Components, error) {
// 移除连字符并验证长度
cleanStr := strings.ReplaceAll(uuidStr, "-", "")
@@ -223,3 +238,21 @@ func ParseUUIDv7FromString(uuidStr string) (*UUIDv7Components, error) {
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))
}