launchpad.net/~rogpeppe/juju-core/500-errgo-fix@v0.0.0-20140213181702-000000002356/utils/uuid.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package utils
     5  
     6  import (
     7  	"crypto/rand"
     8  	"encoding/hex"
     9  	"fmt"
    10  	"io"
    11  	"regexp"
    12  	"strings"
    13  
    14  	"launchpad.net/errgo/errors"
    15  )
    16  
    17  // UUID represent a universal identifier with 16 octets.
    18  type UUID [16]byte
    19  
    20  var validUUID = regexp.MustCompile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[8,9,a,b][0-9a-f]{3}-[0-9a-f]{12}")
    21  
    22  func UUIDFromString(s string) (UUID, error) {
    23  	if !IsValidUUIDString(s) {
    24  		return UUID{}, errors.Newf("invalid UUID: %q", s)
    25  	}
    26  	s = strings.Replace(s, "-", "", 4)
    27  	raw, err := hex.DecodeString(s)
    28  	if err != nil {
    29  		return UUID{}, mask(err)
    30  	}
    31  	var uuid UUID
    32  	copy(uuid[:], raw)
    33  	return uuid, nil
    34  }
    35  
    36  // IsValidUUIDString returns true, if the given string matches a valid UUID (version 4, variant 2).
    37  func IsValidUUIDString(s string) bool {
    38  	return validUUID.MatchString(s)
    39  }
    40  
    41  // NewUUID generates a new version 4 UUID relying only on random numbers.
    42  func NewUUID() (UUID, error) {
    43  	uuid := UUID{}
    44  	if _, err := io.ReadFull(rand.Reader, []byte(uuid[0:16])); err != nil {
    45  		return UUID{}, mask(err)
    46  	}
    47  
    48  	// Set version (4) and variant (2) according to RfC 4122.
    49  	var version byte = 4 << 4
    50  	var variant byte = 8 << 4
    51  	uuid[6] = version | (uuid[6] & 15)
    52  	uuid[8] = variant | (uuid[8] & 15)
    53  	return uuid, nil
    54  }
    55  
    56  // Copy returns a copy of the UUID.
    57  func (uuid UUID) Copy() UUID {
    58  	uuidCopy := uuid
    59  	return uuidCopy
    60  }
    61  
    62  // Raw returns a copy of the UUID bytes.
    63  func (uuid UUID) Raw() [16]byte {
    64  	return [16]byte(uuid)
    65  }
    66  
    67  // String returns a hexadecimal string representation with
    68  // standardized separators.
    69  func (uuid UUID) String() string {
    70  	return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:16])
    71  }