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