Skip to content

Commit

Permalink
feat: update sonyflake (#12)
Browse files Browse the repository at this point in the history
* feat: add sonyflake

* feat: add new id function
  • Loading branch information
wgliyuli authored Oct 30, 2020
1 parent cd1e023 commit c510e72
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
43 changes: 43 additions & 0 deletions sonyflake/new_id.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package sonyflake

import (
"errors"
"time"
)

// NewIdByTime generates a unique ID by time.
// After the Sonyflake time overflows, NewIdByTime returns an error.
// Less than Sonyflake min time, NewIdByTime returns an error.
func (sf *Sonyflake) NewIdByTime(t time.Time) (int64, error) {
if t.UnixNano() < DefaultStartTime.UnixNano() {
return 0, errors.New("min date is 2015/01/01")
}
const maskSequence = uint16(1<<BitLenSequence - 1)

sf.mutex.Lock()
defer sf.mutex.Unlock()

current := currentElapsedTimeWithNow(t, sf.startTime)
if sf.elapsedTime < current {
sf.elapsedTime = current
sf.sequence = 0
} else { // sf.elapsedTime >= current
sf.sequence = (sf.sequence + 1) & maskSequence
if sf.sequence == 0 {
sf.elapsedTime++
overtime := sf.elapsedTime - current
time.Sleep(sleepTimeWithNow(t, overtime))
}
}

return sf.toID()
}

func sleepTimeWithNow(t time.Time, overtime int64) time.Duration {
return time.Duration(overtime)*10*time.Millisecond -
time.Duration(t.UTC().UnixNano()%sonyflakeTimeUnit)*time.Nanosecond
}

func currentElapsedTimeWithNow(t time.Time, startTime int64) int64 {
return toSonyflakeTime(t) - startTime
}
2 changes: 1 addition & 1 deletion sonyflake/sonyflake.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const (
sonyflakeTimeUnit = 1e7 // nsec, i.e. 10 msec
)

var DefaultStartTime = time.Date(2020, 10, 1, 0, 0, 0, 0, time.UTC)
var DefaultStartTime = time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)

// Sonyflake is a distributed unique ID generator.
type Sonyflake struct {
Expand Down

0 comments on commit c510e72

Please sign in to comment.