/
message.go
92 lines (83 loc) · 2.43 KB
/
message.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package rscp
import (
"fmt"
)
type Message struct {
Tag Tag
DataType DataType
Value interface{}
}
// NewMessage creates a new message (infer the data type from the tag).
func NewMessage(tag Tag, value interface{}) *Message {
return &Message{Tag: tag, DataType: tag.DataType(), Value: value}
}
const secretReplaceString = "********"
// String converter function for a message
func (m Message) String() string {
if m.Tag.isSecret() {
return fmt.Sprintf("{ %s %s %v }", m.Tag, m.DataType, secretReplaceString)
}
return fmt.Sprintf("{ %s %s %v }", m.Tag, m.DataType, m.Value)
}
// valueSize returns actual the value size of a message
func (m *Message) valueSize() uint16 {
if m.DataType.length() == 0 && m.DataType != None {
switch v := m.Value.(type) {
default:
panic("not implemented")
case nil:
return 0
case string:
return uint16(len(v))
case []byte:
return uint16(len(v))
case []Message:
return messagesSize(v)
}
} else {
return m.DataType.length()
}
}
// isValidDataType check if the data type is the expected one for the message tag
//
// Note: see Issue https://github.com/spali/go-e3dc/issues/1
// func (m *Message) isValidDataType() bool {
// return m.DataType != m.Tag.DataType()
// }
// validateResponse checks the integrity of the response
//
// must contain a valid tag and data type and the data type must match the value
func (m *Message) validateResponse() error {
if !m.Tag.isResponse() {
return fmt.Errorf("%s: %w", m.Tag, ErrNotAResponseTag)
}
return m.validate()
}
// validate checks the integrity of the message
//
// must contain a valid tag and data type and the data type must match the value
func (m *Message) validate() error {
// check if message data type matches expected data type of the tag
if !m.Tag.IsATag() {
return fmt.Errorf("%s: %w", m.Tag, ErrValidTag)
}
// Note: see Issue https://github.com/spali/go-e3dc/issues/1
//
// else if m.isValidDataType() {
// return fmt.Errorf("%s expects %s, got %s: %w", m.Tag, m.Tag.DataType(), m.DataType, ErrTagDataTypeMismatch)
// }
if !m.DataType.isValidValue(m.Value) {
return fmt.Errorf("expected %T got %T : %w", m.DataType.newEmpty(0), m.Value, ErrDataTypeValueMismatch)
}
if m.valueSize() > RSCP_DATA_MAX_DATA_SIZE {
return ErrRscpDataLimitExceeded
}
if m.DataType == Container {
for i := range m.Value.([]Message) {
if err := m.Value.([]Message)[i].validate(); err != nil {
return err
}
}
}
return nil
}