A simple ID Generator
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.0 KiB

// idg is a go package that provides an entity that emits uniqueish identifiers.
package idg
import (
// This thing contains a channel that when initialized (see NewGenerator)
// 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
type Generator struct {
id chan int64
func NewGenerator() *Generator {
return &Generator{
id: make(chan int64),
// Run is called (typically in a gorotine) to allow for queries to be made
// against Generator.id throgh the Hash method.
func (idg *Generator) Run() {
var i int64
for i = 0; ; i++ {
idg.id <- i
// Hash is the method used by a properly instantiated Generator that gives
// fairly unique strings. They are currently truncated md5 hashes of the time
// plus a unique counter
func (id *Generator) Hash() string {
h := md5.New()
ns := time.Now().UnixNano() + <-id.id
io.WriteString(h, fmt.Sprintf("%d", ns))
return fmt.Sprintf("%x", h.Sum(nil))[:8]