github.com/Prakhar-Agarwal-byte/moby@v0.0.0-20231027092010-a14e3e8ab87e/pkg/stringid/stringid.go (about) 1 // Package stringid provides helper functions for dealing with string identifiers 2 package stringid // import "github.com/Prakhar-Agarwal-byte/moby/pkg/stringid" 3 4 import ( 5 "crypto/rand" 6 "encoding/hex" 7 "errors" 8 "regexp" 9 "strconv" 10 "strings" 11 ) 12 13 const ( 14 shortLen = 12 15 fullLen = 64 16 ) 17 18 var ( 19 validShortID = regexp.MustCompile("^[a-f0-9]{12}$") 20 validHex = regexp.MustCompile(`^[a-f0-9]{64}$`) 21 ) 22 23 // IsShortID determines if id has the correct format and length for a short ID. 24 // It checks the IDs length and if it consists of valid characters for IDs (a-f0-9). 25 func IsShortID(id string) bool { 26 if len(id) != shortLen { 27 return false 28 } 29 return validShortID.MatchString(id) 30 } 31 32 // TruncateID returns a shorthand version of a string identifier for convenience. 33 // A collision with other shorthands is very unlikely, but possible. 34 // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller 35 // will need to use a longer prefix, or the full-length Id. 36 func TruncateID(id string) string { 37 if i := strings.IndexRune(id, ':'); i >= 0 { 38 id = id[i+1:] 39 } 40 if len(id) > shortLen { 41 id = id[:shortLen] 42 } 43 return id 44 } 45 46 // GenerateRandomID returns a unique id. 47 func GenerateRandomID() string { 48 b := make([]byte, 32) 49 for { 50 if _, err := rand.Read(b); err != nil { 51 panic(err) // This shouldn't happen 52 } 53 id := hex.EncodeToString(b) 54 // if we try to parse the truncated for as an int and we don't have 55 // an error then the value is all numeric and causes issues when 56 // used as a hostname. ref #3869 57 if _, err := strconv.ParseInt(TruncateID(id), 10, 64); err == nil { 58 continue 59 } 60 return id 61 } 62 } 63 64 // ValidateID checks whether an ID string is a valid, full-length image ID. 65 func ValidateID(id string) error { 66 if len(id) != fullLen { 67 return errors.New("image ID '" + id + "' is invalid") 68 } 69 if !validHex.MatchString(id) { 70 return errors.New("image ID '" + id + "' is invalid") 71 } 72 return nil 73 }