-
Notifications
You must be signed in to change notification settings - Fork 467
/
hexbytes.go
41 lines (35 loc) · 848 Bytes
/
hexbytes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package chezmoi
import (
"encoding/hex"
)
// A HexBytes is a []byte which is marshaled as a hex string.
type HexBytes []byte
// Bytes returns h as a []byte.
func (h HexBytes) Bytes() []byte {
return []byte(h)
}
// MarshalText implements encoding.TextMarshaler.MarshalText.
func (h HexBytes) MarshalText() ([]byte, error) {
if len(h) == 0 {
return nil, nil
}
result := make([]byte, hex.EncodedLen(len(h)))
hex.Encode(result, h)
return result, nil
}
// UnmarshalText implements encoding.TextUnmarshaler.UnmarshalText.
func (h *HexBytes) UnmarshalText(text []byte) error {
if len(text) == 0 {
*h = nil
return nil
}
result := make([]byte, hex.DecodedLen(len(text)))
if _, err := hex.Decode(result, text); err != nil {
return err
}
*h = result
return nil
}
func (h HexBytes) String() string {
return hex.EncodeToString(h)
}