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