Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support generating id with custom time. #45

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions sonyflake.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,16 @@ func NewSonyflake(st Settings) *Sonyflake {
// NextID generates a next unique ID.
// After the Sonyflake time overflows, NextID returns an error.
func (sf *Sonyflake) NextID() (uint64, error) {
return sf.NextIDWithCustomNow(time.Now())
}

func (sf *Sonyflake) NextIDWithCustomNow(now time.Time) (uint64, error) {
const maskSequence = uint16(1<<BitLenSequence - 1)

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

current := currentElapsedTime(sf.startTime)
current := currentElapsedTime(now, sf.startTime)
if sf.elapsedTime < current {
sf.elapsedTime = current
sf.sequence = 0
Expand All @@ -116,8 +120,8 @@ func toSonyflakeTime(t time.Time) int64 {
return t.UTC().UnixNano() / sonyflakeTimeUnit
}

func currentElapsedTime(startTime int64) int64 {
return toSonyflakeTime(time.Now()) - startTime
func currentElapsedTime(now time.Time, startTime int64) int64 {
return toSonyflakeTime(now) - startTime
}

func sleepTime(overtime int64) time.Duration {
Expand Down