github.com/snowflakedb/gosnowflake@v1.9.0/uuid.go (about)

     1  // Copyright (c) 2022 Snowflake Computing Inc. All rights reserved.
     2  
     3  package gosnowflake
     4  
     5  import (
     6  	"crypto/rand"
     7  	"fmt"
     8  	"strconv"
     9  )
    10  
    11  const rfc4122 = 0x40
    12  
    13  // UUID is a RFC4122 compliant uuid type
    14  type UUID [16]byte
    15  
    16  var nilUUID UUID
    17  
    18  // NewUUID creates a new snowflake UUID
    19  func NewUUID() UUID {
    20  	var u UUID
    21  	rand.Read(u[:])
    22  	u[8] = (u[8] | rfc4122) & 0x7F
    23  
    24  	var version byte = 4
    25  	u[6] = (u[6] & 0xF) | (version << 4)
    26  	return u
    27  }
    28  
    29  func getChar(str string) byte {
    30  	i, _ := strconv.ParseUint(str, 16, 8)
    31  	return byte(i)
    32  }
    33  
    34  // ParseUUID parses a string of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx into its UUID form
    35  func ParseUUID(str string) UUID {
    36  	return UUID{
    37  		getChar(str[0:2]), getChar(str[2:4]), getChar(str[4:6]), getChar(str[6:8]),
    38  		getChar(str[9:11]), getChar(str[11:13]),
    39  		getChar(str[14:16]), getChar(str[16:18]),
    40  		getChar(str[19:21]), getChar(str[21:23]),
    41  		getChar(str[24:26]), getChar(str[26:28]), getChar(str[28:30]), getChar(str[30:32]), getChar(str[32:34]), getChar(str[34:36]),
    42  	}
    43  }
    44  
    45  func (u UUID) String() string {
    46  	return fmt.Sprintf("%x-%x-%x-%x-%x", u[0:4], u[4:6], u[6:8], u[8:10], u[10:])
    47  }