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.

43 lines
1002 B

  1. package server
  2. import (
  3. "crypto/md5"
  4. "fmt"
  5. "io"
  6. "time"
  7. )
  8. // This thing contains a channel that when initialized (see NewIdGenerator)
  9. // will return a bunch of (as best as I can tell) unique md5 hashes.
  10. //
  11. // we use this for naming players, games, etc.
  12. //
  13. // It will consume a single goroutine
  14. type IdGenerator struct {
  15. id chan int64
  16. }
  17. func NewIdGenerator() *IdGenerator {
  18. return &IdGenerator{
  19. id: make(chan int64),
  20. }
  21. }
  22. // Run is called (typically in a gorotine) to allow for queries to be made
  23. // against IdGenerator.id throgh the Hash method.
  24. func (idg *IdGenerator) Run() {
  25. var i int64
  26. for i = 0; ; i++ {
  27. idg.id <- i
  28. }
  29. }
  30. // Hash is the method used by a properly instantiated IdGenerator that gives
  31. // fairly unique strings. They are currently truncated md5 hashes of the time
  32. // plus a unique counter
  33. func (id *IdGenerator) Hash() string {
  34. h := md5.New()
  35. ns := time.Now().UnixNano() + <-id.id
  36. io.WriteString(h, fmt.Sprintf("%d", ns))
  37. return fmt.Sprintf("%x", h.Sum(nil))[:8]
  38. }