diff options
Diffstat (limited to 'internal/command/objectid.go')
-rw-r--r-- | internal/command/objectid.go | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/internal/command/objectid.go b/internal/command/objectid.go new file mode 100644 index 0000000..6eda868 --- /dev/null +++ b/internal/command/objectid.go @@ -0,0 +1,47 @@ +package command + +import ( + "encoding/binary" + "encoding/hex" + "math/rand" + "time" +) + +var iterator uint64 + +func init() { + rand.Seed(time.Now().UnixMicro()) + iterator = rand.Uint64() +} + +func NewObjectID() ObjectID { + iterator++ + p1 := uint64(time.Now().UnixMicro()) + p2 := iterator + p3 := rand.Uint64() + r := ObjectID{} + r = binary.BigEndian.AppendUint64(r, p1) + r = binary.BigEndian.AppendUint64(r, p2) + r = binary.BigEndian.AppendUint64(r, p3) + return r +} + +type ObjectID []byte + +func (o ObjectID) MarshalJSON() ([]byte, error) { + res := make([]byte, 0, hex.EncodedLen(len(o))) + hex.Encode(res, o) + return res, nil +} + +func (o ObjectID) String() string { + return hex.EncodeToString(o) +} + +func (o ObjectID) Time() time.Time { + if len(o) < 8 { + return time.Time{} + } + t := o[:8] + return time.UnixMicro(int64(binary.BigEndian.Uint64(t))) +} |