Skip to content
This repository was archived by the owner on Feb 19, 2025. It is now read-only.

Commit 35ec5eb

Browse files
author
Batyrkhan Koshenov
committed
decoders/utils.go: add ReadUint16/32 funcs to avoid allocs when reading from buffer
Signed-off-by: Batyrkhan Koshenov <[email protected]>
1 parent 0ac9991 commit 35ec5eb

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

decoders/utils/utils.go

+39
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package utils
22

33
import (
4+
"bytes"
45
"encoding/binary"
56
"io"
67
)
@@ -14,3 +15,41 @@ func BinaryDecoder(payload io.Reader, dests ...interface{}) error {
1415
}
1516
return nil
1617
}
18+
19+
// ReadUint16FromBuffer reads Uint16 value from buffer and returns
20+
// boolean flag telling if it was a success.
21+
//
22+
// Value is treated as big endian.
23+
func ReadUint16FromBuffer(b *bytes.Buffer, x *uint16) bool {
24+
var buf [2]byte
25+
26+
for i := range buf {
27+
bt, err := b.ReadByte()
28+
if err != nil {
29+
return false
30+
}
31+
buf[i] = bt
32+
}
33+
34+
*x = binary.BigEndian.Uint16(buf[:])
35+
return true
36+
}
37+
38+
// ReadUint32FromBuffer reads Uint32 value from buffer and returns
39+
// boolean flag telling if it was a success.
40+
//
41+
// Value is treated as big endian.
42+
func ReadUint32FromBuffer(b *bytes.Buffer, x *uint32) bool {
43+
var buf [4]byte
44+
45+
for i := range buf {
46+
bt, err := b.ReadByte()
47+
if err != nil {
48+
return false
49+
}
50+
buf[i] = bt
51+
}
52+
53+
*x = binary.BigEndian.Uint32(buf[:])
54+
return true
55+
}

0 commit comments

Comments
 (0)