Parse decodes s into a UUID or returns an error if it cannot be parsed. Both the standard UUID forms defined in RFC 4122 (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) are decoded. In addition, Parse accepts non-standard strings such as the raw hex encodin
(s string)
| 66 | // examined in the latter case. Parse should not be used to validate strings as |
| 67 | // it parses non-standard encodings as indicated above. |
| 68 | func Parse(s string) (UUID, error) { |
| 69 | var uuid UUID |
| 70 | switch len(s) { |
| 71 | // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
| 72 | case 36: |
| 73 | |
| 74 | // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
| 75 | case 36 + 9: |
| 76 | if !strings.EqualFold(s[:9], "urn:uuid:") { |
| 77 | return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9]) |
| 78 | } |
| 79 | s = s[9:] |
| 80 | |
| 81 | // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} |
| 82 | case 36 + 2: |
| 83 | s = s[1:] |
| 84 | |
| 85 | // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx |
| 86 | case 32: |
| 87 | var ok bool |
| 88 | for i := range uuid { |
| 89 | uuid[i], ok = xtob(s[i*2], s[i*2+1]) |
| 90 | if !ok { |
| 91 | return uuid, errors.New("invalid UUID format") |
| 92 | } |
| 93 | } |
| 94 | return uuid, nil |
| 95 | default: |
| 96 | return uuid, invalidLengthError{len(s)} |
| 97 | } |
| 98 | // s is now at least 36 bytes long |
| 99 | // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
| 100 | if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { |
| 101 | return uuid, errors.New("invalid UUID format") |
| 102 | } |
| 103 | for i, x := range [16]int{ |
| 104 | 0, 2, 4, 6, |
| 105 | 9, 11, |
| 106 | 14, 16, |
| 107 | 19, 21, |
| 108 | 24, 26, 28, 30, 32, 34, |
| 109 | } { |
| 110 | v, ok := xtob(s[x], s[x+1]) |
| 111 | if !ok { |
| 112 | return uuid, errors.New("invalid UUID format") |
| 113 | } |
| 114 | uuid[i] = v |
| 115 | } |
| 116 | return uuid, nil |
| 117 | } |
| 118 | |
| 119 | // ParseBytes is like Parse, except it parses a byte slice instead of a string. |
| 120 | func ParseBytes(b []byte) (UUID, error) { |