From 5e215b925788d9fe2be06b0259d0f654cf04071b Mon Sep 17 00:00:00 2001 From: Paul Mach Date: Sun, 25 Aug 2013 22:41:58 -0700 Subject: [PATCH] Remove depenance on external libs for unique id --- client/client.go | 2 +- client/id.go | 34 +++++++++++++--------------------- client/id_test.go | 18 ++++++++++++++++++ 3 files changed, 32 insertions(+), 22 deletions(-) create mode 100644 client/id_test.go diff --git a/client/client.go b/client/client.go index b0265c6..1fcb142 100644 --- a/client/client.go +++ b/client/client.go @@ -20,7 +20,7 @@ var ( ) func init() { - IdGen = NewObjectId() + IdGen = NewAutoIncId() } // Status handler diff --git a/client/id.go b/client/id.go index 1b86751..1afbaf0 100644 --- a/client/id.go +++ b/client/id.go @@ -1,37 +1,29 @@ package client import ( - "strconv" - "labix.org/v2/mgo/bson" - "github.com/mikespook/golib/autoinc" + "strconv" + "sync/atomic" + "time" ) type IdGenerator interface { - Id() string -} - -// ObjectId -type objectId struct { - bson.ObjectId -} - -func (id *objectId) Id() string { - return id.Hex() -} - -func NewObjectId() IdGenerator { - return &objectId{bson.NewObjectId()} + Id() string } // AutoIncId type autoincId struct { - *autoinc.AutoInc + value int64 } -func (id *autoincId) Id() string { - return strconv.Itoa(id.AutoInc.Id()) +func (ai *autoincId) Id() string { + next := atomic.AddInt64(&ai.value, 1) + return strconv.FormatInt(next, 10) } func NewAutoIncId() IdGenerator { - return &autoincId{autoinc.New(1, 1)} + // we'll consider the nano fraction of a second at startup unique + // and count up from there. + return &autoincId{ + value: int64(time.Now().Nanosecond()) << 32, + } } diff --git a/client/id_test.go b/client/id_test.go new file mode 100644 index 0000000..399d217 --- /dev/null +++ b/client/id_test.go @@ -0,0 +1,18 @@ +package client + +import ( + "testing" +) + +func TestAutoInc(t *testing.T) { + ai := NewAutoIncId() + + previous := ai.Id() + for i := 0; i < 10; i++ { + id := ai.Id() + if id == previous { + t.Errorf("Id not unique, previous and current %s", id) + } + previous = id + } +}