| 10 | ) |
| 11 | |
| 12 | func TestWrite(t *testing.T) { |
| 13 | type Subtree struct { |
| 14 | SubA uint32 |
| 15 | SubB []uint8 |
| 16 | } |
| 17 | |
| 18 | structure := struct { |
| 19 | A uint8 |
| 20 | Z uint32 `encoding:"omit"` |
| 21 | B uint16 |
| 22 | C uint32 |
| 23 | D uint64 |
| 24 | _ uint8 |
| 25 | E []uint16 |
| 26 | F Subtree |
| 27 | G []Subtree |
| 28 | }{ |
| 29 | 0xf8, |
| 30 | 0x01234567, |
| 31 | 0x1234, |
| 32 | 0x56789ABC, |
| 33 | 0x0102030405060708, |
| 34 | 0x12, |
| 35 | []uint16{0x0E, 0x02FF}, |
| 36 | Subtree{0x11223344, []uint8{9, 8, 7, 6, 5, 4, 3, 2, 1}}, |
| 37 | []Subtree{{0x01, []uint8{1, 2, 3, 4}}, {0x02, []uint8{5, 6, 7, 8}}}, |
| 38 | } |
| 39 | expected := []byte{ |
| 40 | 0xf8, |
| 41 | 0x12, 0x34, |
| 42 | 0x56, 0x78, 0x9A, 0xBC, |
| 43 | 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, |
| 44 | 0x00, |
| 45 | 0x00, 0x0E, 0x02, 0xFF, |
| 46 | 0x11, 0x22, 0x33, 0x44, 9, 8, 7, 6, 5, 4, 3, 2, 1, |
| 47 | 0x00, 0x00, 0x00, 0x01, 1, 2, 3, 4, 0x00, 0x00, 0x00, 0x02, 5, 6, 7, 8, |
| 48 | } |
| 49 | assert.Equal(t, len(expected), wireSize(structure)) |
| 50 | |
| 51 | raw := make([]byte, len(expected)) |
| 52 | buffer := packetBuffer{bytes: raw} |
| 53 | err := buffer.write(structure) |
| 54 | assert.NoError(t, err) |
| 55 | assert.Equal(t, expected, raw) |
| 56 | |
| 57 | // Check for overflow |
| 58 | raw = make([]byte, len(expected)-1) |
| 59 | buffer = packetBuffer{bytes: raw} |
| 60 | err = buffer.write(structure) |
| 61 | assert.ErrorIs(t, err, errWrongMarshalSize) |
| 62 | } |
| 63 | |
| 64 | func TestReadUint8(t *testing.T) { |
| 65 | const expected = 0x01 |