Bladeren bron

Remove depenance on external libs for unique id

tags/0.2
Paul Mach 10 jaren geleden
bovenliggende
commit
5e215b9257
3 gewijzigde bestanden met toevoegingen van 32 en 22 verwijderingen
  1. +1
    -1
      client/client.go
  2. +13
    -21
      client/id.go
  3. +18
    -0
      client/id_test.go

+ 1
- 1
client/client.go Bestand weergeven

@@ -20,7 +20,7 @@ var (
)

func init() {
IdGen = NewObjectId()
IdGen = NewAutoIncId()
}

// Status handler


+ 13
- 21
client/id.go Bestand weergeven

@@ -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,
}
}

+ 18
- 0
client/id_test.go Bestand weergeven

@@ -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
}
}

Laden…
Annuleren
Opslaan