git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/guid/uuid.go (about) 1 package guid 2 3 import "encoding/hex" 4 5 // xvalues returns the value of a byte as a hexadecimal digit or 255. 6 var xvalues = [256]byte{ 7 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 8 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 9 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 11 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 12 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 13 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 14 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 16 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 17 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 18 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 19 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 20 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 21 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 22 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 23 } 24 25 // UUIDString returns the UUID string form of GUID, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 26 func (guid GUID) ToUuidString() string { 27 var dst [36]byte 28 29 hex.Encode(dst[:], guid[:4]) 30 dst[8] = '-' 31 hex.Encode(dst[9:13], guid[4:6]) 32 dst[13] = '-' 33 hex.Encode(dst[14:18], guid[6:8]) 34 dst[18] = '-' 35 hex.Encode(dst[19:23], guid[8:10]) 36 dst[23] = '-' 37 hex.Encode(dst[24:], guid[10:]) 38 39 return string(dst[:]) 40 } 41 42 // Parse decodes s into a GUID as an UUID or returns an error. 43 // The form shoud be: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 44 func ParseUuidString(input string) (guid GUID, err error) { 45 if len(input) != 36 { 46 err = ErrUuidIsNotValid 47 return 48 } 49 // input must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 50 if input[8] != '-' || input[13] != '-' || input[18] != '-' || input[23] != '-' { 51 err = ErrUuidIsNotValid 52 return 53 } 54 55 for i, x := range [16]int{ 56 0, 2, 4, 6, 57 9, 11, 58 14, 16, 59 19, 21, 60 24, 26, 28, 30, 32, 34} { 61 v, ok := xtob(input[x], input[x+1]) 62 if !ok { 63 err = ErrUuidIsNotValid 64 return 65 } 66 guid[i] = v 67 } 68 69 return 70 } 71 72 // xtob converts hex characters x1 and x2 into a byte. 73 func xtob(x1, x2 byte) (byte, bool) { 74 b1 := xvalues[x1] 75 b2 := xvalues[x2] 76 return (b1 << 4) | b2, b1 != 255 && b2 != 255 77 }