-
Notifications
You must be signed in to change notification settings - Fork 0
/
hex.go
65 lines (55 loc) · 1014 Bytes
/
hex.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// SPDX-License-Identifier: Apache-2.0
// Copyright © 2022 Wrangle Ltd
package payload
import (
"encoding/hex"
"fmt"
)
type Hex [16]byte
func (x *Hex) String() string {
return hex.EncodeToString(x[:])
}
func (x *Hex) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%x"`, *x)), nil
}
func (x *Hex) UnmarshalJSON(b []byte) error {
b = b[1 : len(b)-1]
_, err := hex.Decode((*x)[:], b)
return err
}
func AppendHex(sl []*Hex, b []byte) []*Hex {
if b == nil {
return append(sl, nil)
}
h := &Hex{}
copy((*h)[:], b)
return append(sl, h)
}
func HexSliceToBytesSlice(sl []*Hex) [][]byte {
b := make([][]byte, len(sl))
for i, v := range sl {
if v == nil {
continue
}
b[i] = (*v)[:]
}
return b
}
func BytesSliceToHexSlice(sl [][]byte) []*Hex {
if len(sl) == 0 {
return nil
}
b := make([]*Hex, len(sl))
for i, v := range sl {
b[i] = BytesToHex(v)
}
return b
}
func BytesToHex(b []byte) *Hex {
if b == nil {
return nil
}
h := &Hex{}
copy((*h)[:], b)
return h
}