implement a WriteUintN function

This commit is contained in:
Marten Seemann
2018-11-26 16:58:11 +07:00
parent faed2ba30a
commit 52380835b9
3 changed files with 35 additions and 0 deletions

View File

@@ -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() { Context("ReadUintN", func() {
It("reads n bytes", func() { It("reads n bytes", func() {
m := map[uint8]uint64{ m := map[uint8]uint64{

View File

@@ -11,6 +11,7 @@ type ByteOrder interface {
ReadUint32(io.ByteReader) (uint32, error) ReadUint32(io.ByteReader) (uint32, error)
ReadUint16(io.ByteReader) (uint16, error) ReadUint16(io.ByteReader) (uint16, error)
WriteUintN(b *bytes.Buffer, length uint8, value uint64)
WriteUint32(*bytes.Buffer, uint32) WriteUint32(*bytes.Buffer, uint32)
WriteUint16(*bytes.Buffer, uint16) WriteUint16(*bytes.Buffer, uint16)
} }

View File

@@ -57,6 +57,12 @@ func (bigEndian) ReadUint16(b io.ByteReader) (uint16, error) {
return uint16(b1) + uint16(b2)<<8, nil 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 // WriteUint32 writes a uint32
func (bigEndian) WriteUint32(b *bytes.Buffer, i uint32) { func (bigEndian) WriteUint32(b *bytes.Buffer, i uint32) {
b.Write([]byte{uint8(i >> 24), uint8(i >> 16), uint8(i >> 8), uint8(i)}) b.Write([]byte{uint8(i >> 24), uint8(i >> 16), uint8(i >> 8), uint8(i)})