/uuid.go
Go | 77 lines | 32 code | 14 blank | 31 comment | 4 complexity | 06646ec5e4196c40deebafd43ae1aa93 MD5 | raw file
- //This pkg implements uuid v4 only.
- package uuid
- import (
- "crypto/rand"
- "log"
- "fmt"
- "bytes"
- "regexp"
- )
- // octet == index: octets inclusive on both ends.
- // |octect 0 - 3 | - time_low: The low fields of the timestamp.
- //
- // |octect 4 - 5 | - time_mid: The mid fields of the timestamp.
- //
- // |octect 6 - 7 | - time_hi_and_version: The high field of the timestamp multiplexed with the version number.
- //
- // |octect 8 | - clock_seq_hi_and_reserved: The high fields of the clock sequence multiplexed with the variant.
- //
- // |octect 9 | - clock_seq_low: The low field of the clock sequence.
- //
- // |octets 10 - 15| - node: The spatially unique node identifier.
- //
- type UUID [16]byte
- // e.g.:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6
- //
- // V4 UUID is of the form: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
- //
- // where x is any hexadecimal digit and y is one of 8, 9, A, or B.
- func (id *UUID) String() string {
- return fmt.Sprintf("%x-%x-%x-%x-%x", id[:4], id[4:6], id[6:8], id[8:10], id[10:])
- }
- func (id *UUID) Bytes() []byte {
- return id[:]
- }
- func Equal(lhs *UUID, rhs *UUID) bool {
- return bytes.Equal(lhs[:], rhs[:])
- }
- //The algorithm is as follows:
- //1. Set the two most significant bits (bits 6 and 7) of the
- // clock_seq_hi_and_reserved to zero and one, respectively.
- //2. Set the four most significant bits (bits 12 through 15) of the
- // time_hi_and_version field to the 4-bit version number from rfc4122, section 4.1.3
- //3. set all other values to randomly (or pseudo-randomly) chosen values.
- //Future improvements: use 2 64 bit values from the rand library.
- func V4() *UUID {
- var retval UUID
- n, err := rand.Read(retval[:])
- if n != 16 || err != nil {
- log.Fatalf("Random bytes read:%d, details:", n, err.Error())
- }
- // Set the four most significant bits (bits 12 through 15) of the
- // time_hi_and_version field to the 4-bit version number from
- // Section 4.1.3.
- retval[6] = (retval[6] & 0xf) | 0x40
- // Set the two most significant bits (bits 6 and 7) of the
- // clock_seq_hi_and_reserved to zero and one, respectively.
- retval[8] = (retval[8] & 0x3f) | 0x80
- return &retval
- }
- func ValidString(s string) bool{
- regex := regexp.MustCompile(`^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$`)
- return regex.MatchString(s)
- }