4 Star 5 Fork 4

Plato/Service-Box-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
custom_generator.go 1.71 KB
一键复制 编辑 原始数据 按行查看 历史
CloudGuan 提交于 2022-04-21 11:23 . update: add uuid model
package custom
import (
"encoding/binary"
"encoding/hex"
"sync/atomic"
)
type (
CustomUUID struct {
cfg *Options
mid uint32
count uint32
}
)
func (c *CustomUUID) New() [16]byte {
var res [16]byte
var mid uint16
num := atomic.AddUint32(&c.count, 1)
if num == 0 {
mid = uint16(atomic.AddUint32(&c.mid, 1) & 0x0000ffff)
} else {
mid = uint16(atomic.LoadUint32(&c.mid) & 0x0000ffff)
}
if mid == 0 && num == 0 {
panic("INVALID ID GEN ")
}
binary.BigEndian.PutUint16(res[0:4], c.cfg.Seed)
binary.BigEndian.PutUint16(res[4:], mid)
binary.BigEndian.PutUint32(res[8:], num)
return res
}
func (c *CustomUUID) New32UUID() uint32 {
num := atomic.AddUint32(&c.count, 1) & 0x0000ffff
if num == 0 {
panic("INVALID ID GEN")
}
return uint32(c.cfg.Seed)<<16 + num
}
func (c *CustomUUID) New64UUID() uint64 {
var mid uint16
num := atomic.AddUint32(&c.count, 1)
if num == 0 {
mid = uint16(atomic.AddUint32(&c.mid, 1) & 0x0000ffff)
} else {
mid = uint16(atomic.LoadUint32(&c.mid) & 0x0000ffff)
}
return uint64(c.cfg.Seed)<<48 + uint64(mid)<<32 + uint64(num)
}
// NewStringUUID will return rfc 2141 uuid
func (c *CustomUUID) NewStringUUID() string {
var dist [36 + 9]byte
res := c.New()
hex.Encode(dist[:], res[0:4])
dist[8] = '-'
hex.Encode(dist[9:13], res[4:6])
dist[13] = '-'
hex.Encode(dist[14:18], res[6:8])
dist[18] = '-'
hex.Encode(dist[19:23], res[8:10])
dist[23] = '-'
hex.Encode(dist[24:], res[10:])
return string(dist[:])
}
func (c *CustomUUID) ParseFromByte(bytes []byte) string {
panic("implement me")
}
func NewCustomUUID(opts ...Option) *CustomUUID {
idGen := &CustomUUID{
cfg: &Options{},
mid: 1,
count: 1,
}
for _, opt := range opts {
opt(idGen.cfg)
}
return idGen
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/dennis-kk/service-box-go.git
git@gitee.com:dennis-kk/service-box-go.git
dennis-kk
service-box-go
Service-Box-go
v0.5.13

搜索帮助