-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdecoder.go
More file actions
48 lines (40 loc) · 1.22 KB
/
decoder.go
File metadata and controls
48 lines (40 loc) · 1.22 KB
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
package data
import (
"encoding/binary"
"io"
"github.com/HyperloopUPV-H8/h9-backend/pkg/abstraction"
)
// Decoder is a decoder for data packets. It uses the decoder defined on the packet descriptor
type Decoder struct {
endianness binary.ByteOrder
idToDescription map[abstraction.PacketId]Descriptor
}
// TODO: improve constructor
// NewDecoder creates a new Decoder
func NewDecoder(endianness binary.ByteOrder) *Decoder {
return &Decoder{
endianness: endianness,
idToDescription: make(map[abstraction.PacketId]Descriptor),
}
}
// SetDescriptor sets the descriptor for the given id
func (decoder *Decoder) SetDescriptor(id abstraction.PacketId, descriptor Descriptor) *Decoder {
decoder.idToDescription[id] = descriptor
return decoder
}
// Decode decodes the next packet for the given id
func (decoder *Decoder) Decode(id abstraction.PacketId, reader io.Reader) (abstraction.Packet, error) {
descriptor, ok := decoder.idToDescription[id]
if !ok {
return nil, ErrUnexpectedId{Id: id}
}
packet := GetPacket(id)
for _, value := range descriptor {
val, err := value.Decode(decoder.endianness, reader)
if err != nil {
return packet, err
}
packet.SetValue(value.Name, val, true)
}
return packet, nil
}