diff --git a/internal/utils/byteoder_big_endian_test.go b/internal/utils/byteoder_big_endian_test.go index 45646236..9ea1f5ad 100644 --- a/internal/utils/byteoder_big_endian_test.go +++ b/internal/utils/byteoder_big_endian_test.go @@ -73,6 +73,34 @@ var _ = Describe("Big Endian encoding / decoding", func() { }) }) + Context("WriteUintN", func() { + It("writes n bytes", func() { + expected := []byte{0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8} + m := map[uint8]uint64{ + 0: 0x0, + 1: 0x01, + 2: 0x0102, + 3: 0x010203, + 4: 0x01020304, + 5: 0x0102030405, + 6: 0x010203040506, + 7: 0x01020304050607, + 8: 0x0102030405060708, + } + for n, val := range m { + b := &bytes.Buffer{} + BigEndian.WriteUintN(b, n, val) + Expect(b.Bytes()).To(Equal(expected[:n])) + } + }) + + It("cuts off the higher order bytes", func() { + b := &bytes.Buffer{} + BigEndian.WriteUintN(b, 2, 0xdeadbeef) + Expect(b.Bytes()).To(Equal([]byte{0xbe, 0xef})) + }) + }) + Context("ReadUintN", func() { It("reads n bytes", func() { m := map[uint8]uint64{ diff --git a/internal/utils/byteorder.go b/internal/utils/byteorder.go index 8cd89934..6b92cfa2 100644 --- a/internal/utils/byteorder.go +++ b/internal/utils/byteorder.go @@ -11,6 +11,7 @@ type ByteOrder interface { ReadUint32(io.ByteReader) (uint32, error) ReadUint16(io.ByteReader) (uint16, error) + WriteUintN(b *bytes.Buffer, length uint8, value uint64) WriteUint32(*bytes.Buffer, uint32) WriteUint16(*bytes.Buffer, uint16) } diff --git a/internal/utils/byteorder_big_endian.go b/internal/utils/byteorder_big_endian.go index b7ef7453..eede9cd7 100644 --- a/internal/utils/byteorder_big_endian.go +++ b/internal/utils/byteorder_big_endian.go @@ -57,6 +57,12 @@ func (bigEndian) ReadUint16(b io.ByteReader) (uint16, error) { return uint16(b1) + uint16(b2)<<8, nil } +func (bigEndian) WriteUintN(b *bytes.Buffer, length uint8, i uint64) { + for j := length; j > 0; j-- { + b.WriteByte(uint8(i >> (8 * (j - 1)))) + } +} + // WriteUint32 writes a uint32 func (bigEndian) WriteUint32(b *bytes.Buffer, i uint32) { b.Write([]byte{uint8(i >> 24), uint8(i >> 16), uint8(i >> 8), uint8(i)})