maeqtt/mqtt/types/Decoding.go

86 lines
1.6 KiB
Go
Raw Normal View History

2021-08-26 15:08:24 +02:00
package types
import (
"bufio"
"encoding/binary"
"errors"
)
func DecodeBits(r *bufio.Reader) ([8]bool, error) {
bitflags, err := r.ReadByte()
if err != nil {
return [8]bool{}, err
}
var res [8]bool
for i := range res {
res[i] = (bitflags>>i)&1 == 1
}
return res, nil
}
func DecodeUint16(r *bufio.Reader) (uint16, error) {
buf := make([]byte, 2)
_, err := r.Read(buf)
if err != nil {
return 0, err
}
return binary.BigEndian.Uint16(buf), nil
}
func DecodeUint32(r *bufio.Reader) (uint32, error) {
buf := make([]byte, 4)
_, err := r.Read(buf)
if err != nil {
return 0, err
}
return binary.BigEndian.Uint32(buf), nil
}
func DecodeDataWithVarIntLen(r *bufio.Reader) ([]byte, error) {
len, err := DecodeVariableByteInt(r)
if err != nil {
return []byte{}, err
}
buffer := make([]byte, len)
_, err = r.Read(buffer)
return buffer, err
}
func DecodeBinaryData(r *bufio.Reader) ([]byte, error) {
len, err := DecodeUint16(r)
if err != nil {
return []byte{}, err
}
buffer := make([]byte, len)
_, err = r.Read(buffer)
return buffer, err
}
func DecodeUTF8String(r *bufio.Reader) (string, error) {
binary, err := DecodeBinaryData(r)
return string(binary[:]), err
}
func DecodeVariableByteInt(r *bufio.Reader) (value uint32, err error) {
multiplier := uint32(1)
value = 0
for {
encodedByte, err := r.ReadByte()
if err != nil {
return value, err
}
value += uint32((encodedByte & 127)) * multiplier
if multiplier > 128*128*128 {
return value, errors.New("Malformed Variable Byte Integer")
}
multiplier *= 128
if encodedByte&128 == 0 {
break
}
}
return value, nil
}