@@ -25,29 +25,23 @@ import (
2525type Nibbles []byte
2626
2727const (
28- // evenIndicator for serialization when the last nibble in a byte array
29- // is part of the nibble array.
30- evenIndicator = 0x01
31- // oddIndicator for when it is not .
32- oddIndicator = 0x03
28+ // oddIndicator for serialization when the last nibble in a byte array
29+ // is not part of the nibble array.
30+ oddIndicator = 0x01
31+ // evenIndicator for when it is.
32+ evenIndicator = 0x03
3333)
3434
3535// MakeNibbles returns a nibble array from the byte array. If oddLength is true,
36- // the last 4 bits of the last byte of the array are ignored.
37- func MakeNibbles (data []byte , oddLength bool ) Nibbles {
38- return Unpack (data , oddLength )
39- }
40-
41- // Unpack the byte array into a nibble array. If oddLength is true, the last 4
42- // bits of the last byte of the array are ignored. Allocates a new byte
43- // slice.
36+ // the last 4 bits of the last byte of the array are ignored.
4437//
4538// [0x12, 0x30], true -> [0x1, 0x2, 0x3]
4639// [0x12, 0x34], false -> [0x1, 0x2, 0x3, 0x4]
4740// [0x12, 0x34], true -> [0x1, 0x2, 0x3] <-- last byte last 4 bits ignored
4841// [], false -> []
4942// never to be called with [], true
50- func Unpack (data []byte , oddLength bool ) Nibbles {
43+ // Allocates a new byte slice.
44+ func MakeNibbles (data []byte , oddLength bool ) Nibbles {
5145 length := len (data ) * 2
5246 if oddLength {
5347 length = length - 1
@@ -142,11 +136,11 @@ func Serialize(nyb Nibbles) (data []byte) {
142136 output := make ([]byte , length + 1 )
143137 copy (output , p )
144138 if h {
145- // 0x1 is the arbitrary odd length indicator
146- output [length ] = evenIndicator
147- } else {
148- // 0x3 is the arbitrary even length indicator
139+ // 0x01 is the odd length indicator
149140 output [length ] = oddIndicator
141+ } else {
142+ // 0x03 is the even length indicator
143+ output [length ] = evenIndicator
150144 }
151145
152146 return output
@@ -159,10 +153,13 @@ func Deserialize(encoding []byte) (Nibbles, error) {
159153 if length == 0 {
160154 return nil , errors .New ("invalid encoding" )
161155 }
162- if encoding [length - 1 ] == evenIndicator {
163- ns = Unpack (encoding [:length - 1 ], true )
164- } else if encoding [length - 1 ] == oddIndicator {
165- ns = Unpack (encoding [:length - 1 ], false )
156+ if encoding [length - 1 ] == oddIndicator {
157+ if length == 1 {
158+ return nil , errors .New ("invalid encoding" )
159+ }
160+ ns = MakeNibbles (encoding [:length - 1 ], true )
161+ } else if encoding [length - 1 ] == evenIndicator {
162+ ns = MakeNibbles (encoding [:length - 1 ], false )
166163 } else {
167164 return nil , errors .New ("invalid encoding" )
168165 }
0 commit comments