From 9cb615b023d376fe5590ade4f92e11a9482b69cb Mon Sep 17 00:00:00 2001 From: Achille Date: Tue, 24 Oct 2017 16:38:42 -0700 Subject: [PATCH] add sequence bounds (#21) --- sequence.go | 19 +++++++++++++++++-- sequence_test.go | 8 ++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/sequence.go b/sequence.go index d8c7792..9f1c33a 100644 --- a/sequence.go +++ b/sequence.go @@ -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 } diff --git a/sequence_test.go b/sequence_test.go index 2f9f62e..a341709 100644 --- a/sequence_test.go +++ b/sequence_test.go @@ -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 { @@ -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") + } }