idg/id.go

45 lines
1.0 KiB
Go
Raw Permalink Normal View History

2014-11-24 14:52:23 -08:00
// idg is a go package that provides an entity that emits uniqueish identifiers.
2014-08-03 01:02:16 -07:00
package idg
import (
"crypto/md5"
"fmt"
"io"
"time"
)
2014-11-24 14:39:34 -08:00
// This thing contains a channel that when initialized (see NewGenerator)
2014-08-03 01:02:16 -07:00
// will return a bunch of (as best as I can tell) unique md5 hashes.
//
// we use this for naming players, games, etc.
//
// It will consume a single goroutine
2014-11-24 14:39:34 -08:00
type Generator struct {
2014-08-03 01:02:16 -07:00
id chan int64
}
2014-11-24 14:39:34 -08:00
func NewGenerator() *Generator {
return &Generator{
2014-08-03 01:02:16 -07:00
id: make(chan int64),
}
}
// Run is called (typically in a gorotine) to allow for queries to be made
2014-11-24 14:39:34 -08:00
// against Generator.id throgh the Hash method.
func (idg *Generator) Run() {
2014-08-03 01:02:16 -07:00
var i int64
for i = 0; ; i++ {
idg.id <- i
}
}
2014-11-24 14:39:34 -08:00
// Hash is the method used by a properly instantiated Generator that gives
2014-08-03 01:02:16 -07:00
// fairly unique strings. They are currently truncated md5 hashes of the time
// plus a unique counter
2014-11-24 14:39:34 -08:00
func (id *Generator) Hash() string {
2014-08-03 01:02:16 -07:00
h := md5.New()
ns := time.Now().UnixNano() + <-id.id
io.WriteString(h, fmt.Sprintf("%d", ns))
return fmt.Sprintf("%x", h.Sum(nil))[:8]
}