forked from libp2p/go-libp2p
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hex.go
70 lines (64 loc) · 1.88 KB
/
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
66
67
68
69
70
package libp2pwebrtc
// The code in this file is adapted from the Go standard library's hex package.
// As found in https://cs.opensource.google/go/go/+/refs/tags/go1.20.2:src/encoding/hex/hex.go
//
// The reason we adapted the original code is to allow us to deal with interspersed requirements
// while at the same time hex encoding/decoding, without having to do so in two passes.
import (
"encoding/hex"
"errors"
)
// encodeInterspersedHex encodes a byte slice into a string of hex characters,
// separating each encoded byte with a colon (':').
//
// Example: { 0x01, 0x02, 0x03 } -> "01:02:03"
func encodeInterspersedHex(src []byte) string {
if len(src) == 0 {
return ""
}
s := hex.EncodeToString(src)
n := len(s)
// Determine number of colons
colons := n / 2
if n%2 == 0 {
colons--
}
buffer := make([]byte, n+colons)
for i, j := 0, 0; i < n; i, j = i+2, j+3 {
copy(buffer[j:j+2], s[i:i+2])
if j+3 < len(buffer) {
buffer[j+2] = ':'
}
}
return string(buffer)
}
var errUnexpectedIntersperseHexChar = errors.New("unexpected character in interspersed hex string")
// decodeInterspersedHexFromASCIIString decodes an ASCII string of hex characters into a byte slice,
// where the hex characters are expected to be separated by a colon (':').
//
// NOTE that this function returns an error in case the input string contains non-ASCII characters.
//
// Example: "01:02:03" -> { 0x01, 0x02, 0x03 }
func decodeInterspersedHexFromASCIIString(s string) ([]byte, error) {
n := len(s)
buffer := make([]byte, n/3*2+n%3)
j := 0
for i := 0; i < n; i++ {
if i%3 == 2 {
if s[i] != ':' {
return nil, errUnexpectedIntersperseHexChar
}
} else {
if s[i] == ':' {
return nil, errUnexpectedIntersperseHexChar
}
buffer[j] = s[i]
j++
}
}
dst := make([]byte, hex.DecodedLen(len(buffer)))
if _, err := hex.Decode(dst, buffer); err != nil {
return nil, err
}
return dst, nil
}