2015-02-20 23:48:23 -05:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"encoding/hex"
|
|
|
|
"io"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
|
|
|
// TruncateID returns a shorthand version of a string identifier for convenience.
|
|
|
|
// A collision with other shorthands is very unlikely, but possible.
|
|
|
|
// In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
|
|
|
|
// will need to use a langer prefix, or the full-length Id.
|
|
|
|
func TruncateID(id string) string {
|
|
|
|
shortLen := 12
|
|
|
|
if len(id) < shortLen {
|
|
|
|
shortLen = len(id)
|
|
|
|
}
|
|
|
|
return id[:shortLen]
|
|
|
|
}
|
|
|
|
|
|
|
|
// GenerateRandomID returns an unique id
|
|
|
|
func GenerateRandomID() string {
|
|
|
|
for {
|
|
|
|
id := make([]byte, 32)
|
|
|
|
if _, err := io.ReadFull(rand.Reader, id); err != nil {
|
|
|
|
panic(err) // This shouldn't happen
|
|
|
|
}
|
|
|
|
value := hex.EncodeToString(id)
|
|
|
|
// if we try to parse the truncated for as an int and we don't have
|
|
|
|
// an error then the value is all numberic and causes issues when
|
|
|
|
// used as a hostname. ref #3869
|
|
|
|
if _, err := strconv.ParseInt(TruncateID(value), 10, 64); err == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
}
|
2015-02-25 13:27:14 -05:00
|
|
|
|
|
|
|
func RandomString() string {
|
|
|
|
id := make([]byte, 32)
|
|
|
|
|
|
|
|
if _, err := io.ReadFull(rand.Reader, id); err != nil {
|
|
|
|
panic(err) // This shouldn't happen
|
|
|
|
}
|
|
|
|
return hex.EncodeToString(id)
|
|
|
|
}
|