Skip to content

Commit e09c292

Browse files
committed
Add Map as new primitive type
1 parent 5a5aad8 commit e09c292

File tree

4 files changed

+51
-2
lines changed

4 files changed

+51
-2
lines changed

README.md

+3-2
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,13 @@ developed to be used in [`dtn7-go`][dtn7-go], an implementation of the
66
`cboring` is both boring to use and bored about the amount of data to handle.
77

88

9-
## Non-Features
9+
## Features
1010

11-
- Supports the subset of [CBOR's][cbor] features necessary for [BPv7][bpbis]:
11+
- Supports a selected subset of [CBOR's][cbor] features:
1212
- Unsigned Integer
1313
- Byte and Text String
1414
- Arrays, both of definite and indefinite length
15+
- Maps of definite length
1516
- Booleans
1617
- Small and clear codebase:
1718
- Only works on streams, Go's `io.Reader` or `io.Writer`

major.go

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const (
1313
ByteString MajorType = 0x40
1414
TextString MajorType = 0x60
1515
Array MajorType = 0x80
16+
Map MajorType = 0xA0
1617
SimpleData MajorType = 0xE0
1718
)
1819

primitives.go

+14
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,17 @@ func ReadArrayLength(r io.Reader) (n uint64, err error) {
5555
func WriteArrayLength(n uint64, w io.Writer) error {
5656
return WriteMajors(Array, n, w)
5757
}
58+
59+
/*** Map ***/
60+
61+
// ReadMapPairLength expects a map at the Reader's position and returns the
62+
// amount of pairs stored.
63+
func ReadMapPairLength(r io.Reader) (n uint64, err error) {
64+
return ReadExpectMajors(Map, r)
65+
}
66+
67+
// WriteMapPairLength writes the type definition for a map with the given
68+
// amount of pairs into the Writer.
69+
func WriteMapPairLength(n uint64, w io.Writer) error {
70+
return WriteMajors(Map, n, w)
71+
}

primitives_test.go

+33
Original file line numberDiff line numberDiff line change
@@ -167,3 +167,36 @@ func TestArrayLen(t *testing.T) {
167167
}
168168
}
169169
}
170+
171+
/*** Map ***/
172+
173+
func TestMapPairLen(t *testing.T) {
174+
tests := []struct {
175+
data []byte
176+
len uint64
177+
}{
178+
{[]byte{0xA0}, 0},
179+
{[]byte{0xA1}, 1},
180+
{[]byte{0xB8, 0x19}, 25},
181+
}
182+
183+
for _, test := range tests {
184+
// Read
185+
buff := bytes.NewBuffer(test.data)
186+
if n, err := ReadMapPairLength(buff); err != nil {
187+
t.Fatal(err)
188+
} else if n != test.len {
189+
t.Fatalf("Resulting length %d is not %d", n, test.len)
190+
}
191+
192+
// Write
193+
buff.Reset()
194+
if err := WriteMapPairLength(test.len, buff); err != nil {
195+
t.Fatal(err)
196+
}
197+
198+
if bb := buff.Bytes(); !reflect.DeepEqual(bb, test.data) {
199+
t.Fatalf("Serialized data mismatches: %x != %x", bb, test.data)
200+
}
201+
}
202+
}

0 commit comments

Comments
 (0)