github.com/geniusesgroup/libgo@v0.0.0-20220713101832-828057a9d3d4/user/user.go (about) 1 /* For license and copyright information please see LEGAL file in repository */ 2 3 package user 4 5 import ( 6 "crypto/rand" 7 8 "../binary" 9 "../protocol" 10 "../time/unix" 11 ) 12 13 func NewID(userType protocol.UserType) (id UUID) { 14 var now = unix.Now() 15 id.setSecondElapsed(now.SecondElapsed()) 16 id.setNanoSecondElapsed(now.NanoSecondElapsed()) 17 id[12] = byte(userType) 18 // TODO::: moved to heap: id, Is it any way to prevent heap alloc?? 19 rand.Read(id[13:]) 20 return 21 } 22 23 // 0...7 >> second elapsed 24 // 8...11 >> nano second elapsed 25 // 12...12 >> type 26 // 13...15 >> random id 27 type UUID [16]byte 28 29 func (id UUID) UUID() [16]byte { return id } 30 func (id UUID) Type() protocol.UserType { return protocol.UserType(id[8]) } 31 func (id UUID) ID() [3]byte { return id.id() } 32 func (id UUID) ExistenceTime() protocol.Time { 33 var time unix.Time 34 time.ChangeTo(unix.SecElapsed(id.secondElapsed()), id.nanoSecondElapsed()) 35 return &time 36 } 37 38 func (id UUID) id() (rid [3]byte) { copy(rid[:], id[13:]); return } 39 func (id UUID) secondElapsed() int64 { return int64(binary.LittleEndian.Uint64(id[0:])) } 40 func (id UUID) nanoSecondElapsed() int32 { return int32(binary.LittleEndian.Uint32(id[8:])) } 41 func (id UUID) setSecondElapsed(sec int64) { binary.LittleEndian.PutUint64(id[0:], uint64(sec)) } 42 func (id UUID) setNanoSecondElapsed(nsec int32) { binary.LittleEndian.PutUint32(id[8:], uint32(nsec)) }