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