ParseBytes is like Parse, except it parses a byte slice instead of a string.
(b []byte)
| 146 | |
| 147 | // ParseBytes is like Parse, except it parses a byte slice instead of a string. |
| 148 | func ParseBytes(b []byte) (UUID, error) { |
| 149 | var uuid UUID |
| 150 | switch len(b) { |
| 151 | case 36: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
| 152 | case 36 + 9: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
| 153 | if !bytes.EqualFold(b[:9], []byte("urn:uuid:")) { |
| 154 | return uuid, URNPrefixError{string(b[:9])} |
| 155 | } |
| 156 | b = b[9:] |
| 157 | case 36 + 2: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} |
| 158 | b = b[1:] |
| 159 | case 32: // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx |
| 160 | var ok bool |
| 161 | for i := 0; i < 32; i += 2 { |
| 162 | uuid[i/2], ok = xtob(b[i], b[i+1]) |
| 163 | if !ok { |
| 164 | return uuid, ErrInvalidUUIDFormat |
| 165 | } |
| 166 | } |
| 167 | return uuid, nil |
| 168 | default: |
| 169 | return uuid, invalidLengthError{len(b)} |
| 170 | } |
| 171 | // s is now at least 36 bytes long |
| 172 | // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
| 173 | if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' { |
| 174 | return uuid, ErrInvalidUUIDFormat |
| 175 | } |
| 176 | for i, x := range [16]int{ |
| 177 | 0, 2, 4, 6, |
| 178 | 9, 11, |
| 179 | 14, 16, |
| 180 | 19, 21, |
| 181 | 24, 26, 28, 30, 32, 34, |
| 182 | } { |
| 183 | v, ok := xtob(b[x], b[x+1]) |
| 184 | if !ok { |
| 185 | return uuid, ErrInvalidUUIDFormat |
| 186 | } |
| 187 | uuid[i] = v |
| 188 | } |
| 189 | return uuid, nil |
| 190 | } |
| 191 | |
| 192 | // MustParse is like Parse but panics if the string cannot be parsed. |
| 193 | // It simplifies safe initialization of global variables holding compiled UUIDs. |