github.com/christopherobin/docker@v1.6.2/pkg/common/randomid.go (about)

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