/
binary.go
63 lines (50 loc) · 1.17 KB
/
binary.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package util
import (
"bytes"
"errors"
"fmt"
"io"
"strconv"
)
const (
binaryBase = 2
bitSize = 32
)
// BinaryBufferToBytes turns the data from bytes.Buffer into a slice of bytes.
func BinaryBufferToBytes(binBuffer *bytes.Buffer) ([]byte, error) {
var byteBuffer bytes.Buffer
bufferLen := binBuffer.Len()
if err := validateBufferLength(bufferLen); err != nil {
return nil, err
}
for i := 0; i < bufferLen; i += BitLength {
parsedInt, err := parseInt64(binBuffer)
if err != nil {
return nil, err
}
// returns a nil error
byteBuffer.WriteByte(byte(parsedInt))
}
return byteBuffer.Bytes(), nil
}
func parseInt64(binBuffer *bytes.Buffer) (int64, error) {
byteChunk, err := io.ReadAll(io.LimitReader(binBuffer, BitLength))
if err != nil {
return 0, fmt.Errorf("failed reading from buffer: %w", err)
}
parsedInt, err := strconv.ParseInt(string(byteChunk), binaryBase, bitSize)
if err != nil {
return 0, fmt.Errorf(
"failed to parse %s as a string: %w",
byteChunk,
err,
)
}
return parsedInt, nil
}
func validateBufferLength(bufferLen int) error {
if (bufferLen % BitLength) != 0 {
return errors.New("invalid buffer length")
}
return nil
}