Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame^] | 1 | // Copyright 2016 Google Inc. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package uuid |
| 6 | |
| 7 | import ( |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | ) |
| 11 | |
| 12 | // MarshalText implements encoding.TextMarshaler. |
| 13 | func (u UUID) MarshalText() ([]byte, error) { |
| 14 | if len(u) != 16 { |
| 15 | return nil, nil |
| 16 | } |
| 17 | var js [36]byte |
| 18 | encodeHex(js[:], u) |
| 19 | return js[:], nil |
| 20 | } |
| 21 | |
| 22 | // UnmarshalText implements encoding.TextUnmarshaler. |
| 23 | func (u *UUID) UnmarshalText(data []byte) error { |
| 24 | if len(data) == 0 { |
| 25 | return nil |
| 26 | } |
| 27 | id := Parse(string(data)) |
| 28 | if id == nil { |
| 29 | return errors.New("invalid UUID") |
| 30 | } |
| 31 | *u = id |
| 32 | return nil |
| 33 | } |
| 34 | |
| 35 | // MarshalBinary implements encoding.BinaryMarshaler. |
| 36 | func (u UUID) MarshalBinary() ([]byte, error) { |
| 37 | return u[:], nil |
| 38 | } |
| 39 | |
| 40 | // UnmarshalBinary implements encoding.BinaryUnmarshaler. |
| 41 | func (u *UUID) UnmarshalBinary(data []byte) error { |
| 42 | if len(data) == 0 { |
| 43 | return nil |
| 44 | } |
| 45 | if len(data) != 16 { |
| 46 | return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) |
| 47 | } |
| 48 | var id [16]byte |
| 49 | copy(id[:], data) |
| 50 | *u = id[:] |
| 51 | return nil |
| 52 | } |
| 53 | |
| 54 | // MarshalText implements encoding.TextMarshaler. |
| 55 | func (u Array) MarshalText() ([]byte, error) { |
| 56 | var js [36]byte |
| 57 | encodeHex(js[:], u[:]) |
| 58 | return js[:], nil |
| 59 | } |
| 60 | |
| 61 | // UnmarshalText implements encoding.TextUnmarshaler. |
| 62 | func (u *Array) UnmarshalText(data []byte) error { |
| 63 | id := Parse(string(data)) |
| 64 | if id == nil { |
| 65 | return errors.New("invalid UUID") |
| 66 | } |
| 67 | *u = id.Array() |
| 68 | return nil |
| 69 | } |
| 70 | |
| 71 | // MarshalBinary implements encoding.BinaryMarshaler. |
| 72 | func (u Array) MarshalBinary() ([]byte, error) { |
| 73 | return u[:], nil |
| 74 | } |
| 75 | |
| 76 | // UnmarshalBinary implements encoding.BinaryUnmarshaler. |
| 77 | func (u *Array) UnmarshalBinary(data []byte) error { |
| 78 | if len(data) != 16 { |
| 79 | return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) |
| 80 | } |
| 81 | copy(u[:], data) |
| 82 | return nil |
| 83 | } |