stringid.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Package stringid provides helper functions for dealing with string identifiers
  2. package stringid
  3. import (
  4. "crypto/rand"
  5. "encoding/hex"
  6. "io"
  7. "regexp"
  8. "strconv"
  9. "github.com/docker/docker/pkg/random"
  10. )
  11. const shortLen = 12
  12. var validShortID = regexp.MustCompile("^[a-z0-9]{12}$")
  13. // IsShortID determines if an arbitrary string *looks like* a short ID.
  14. func IsShortID(id string) bool {
  15. return validShortID.MatchString(id)
  16. }
  17. // TruncateID returns a shorthand version of a string identifier for convenience.
  18. // A collision with other shorthands is very unlikely, but possible.
  19. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  20. // will need to use a langer prefix, or the full-length Id.
  21. func TruncateID(id string) string {
  22. trimTo := shortLen
  23. if len(id) < shortLen {
  24. trimTo = len(id)
  25. }
  26. return id[:trimTo]
  27. }
  28. func generateID(crypto bool) string {
  29. b := make([]byte, 32)
  30. r := random.Reader
  31. if crypto {
  32. r = rand.Reader
  33. }
  34. for {
  35. if _, err := io.ReadFull(r, b); err != nil {
  36. panic(err) // This shouldn't happen
  37. }
  38. id := hex.EncodeToString(b)
  39. // if we try to parse the truncated for as an int and we don't have
  40. // an error then the value is all numberic and causes issues when
  41. // used as a hostname. ref #3869
  42. if _, err := strconv.ParseInt(TruncateID(id), 10, 64); err == nil {
  43. continue
  44. }
  45. return id
  46. }
  47. }
  48. // GenerateRandomID returns an unique id.
  49. func GenerateRandomID() string {
  50. return generateID(true)
  51. }
  52. // GenerateNonCryptoID generates unique id without using cryptographically
  53. // secure sources of random.
  54. // It helps you to save entropy.
  55. func GenerateNonCryptoID() string {
  56. return generateID(false)
  57. }