Skip to content

Commit

Permalink
add sequence bounds (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
achille-roussel committed Oct 24, 2017
1 parent 3afe411 commit 9cb615b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
19 changes: 17 additions & 2 deletions sequence.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,21 @@ func (seq *Sequence) Next() (KSUID, error) {
return Nil, errors.New("too many IDs were generated")
}
seq.count++
binary.BigEndian.PutUint16(id[len(id)-2:], uint16(count))
return id, nil
return withSequenceNumber(id, uint16(count)), nil
}

// Bounds returns the inclusive min and max bounds of the KSUIDs that may be
// generated by the sequence. If all ids have been generated already then the
// returned min value is equal to the max.
func (seq *Sequence) Bounds() (min KSUID, max KSUID) {
count := seq.count
if count > math.MaxUint16 {
count = math.MaxUint16
}
return withSequenceNumber(seq.Seed, uint16(count)), withSequenceNumber(seq.Seed, math.MaxUint16)
}

func withSequenceNumber(id KSUID, n uint16) KSUID {
binary.BigEndian.PutUint16(id[len(id)-2:], n)
return id
}
8 changes: 8 additions & 0 deletions sequence_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import (
func TestSequence(t *testing.T) {
seq := Sequence{Seed: New()}

if min, max := seq.Bounds(); min == max {
t.Error("min and max of KSUID range must differ when no ids have been generated")
}

for i := 0; i <= math.MaxUint16; i++ {
id, err := seq.Next()
if err != nil {
Expand All @@ -22,4 +26,8 @@ func TestSequence(t *testing.T) {
if _, err := seq.Next(); err == nil {
t.Fatal("no error returned after exhausting the id generator")
}

if min, max := seq.Bounds(); min != max {
t.Error("after all KSUIDs were generated the min and max must be equal")
}
}

0 comments on commit 9cb615b

Please sign in to comment.