-
-
Notifications
You must be signed in to change notification settings - Fork 133
/
container.go
96 lines (87 loc) · 1.8 KB
/
container.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
93
94
95
96
package proto
import (
"github.com/go-faster/errors"
"github.com/gotd/td/bin"
)
// MessageContainerTypeID is TL type id of MessageContainer.
const MessageContainerTypeID = 0x73f1f8dc
// MessageContainer contains slice of messages.
type MessageContainer struct {
Messages []Message
}
// Encode implements bin.Decoder.
func (m *MessageContainer) Encode(b *bin.Buffer) error {
b.PutID(MessageContainerTypeID)
b.PutInt(len(m.Messages))
for _, msg := range m.Messages {
if err := msg.Encode(b); err != nil {
return err
}
}
return nil
}
// Decode implements bin.Decoder.
func (m *MessageContainer) Decode(b *bin.Buffer) error {
if err := b.ConsumeID(MessageContainerTypeID); err != nil {
return errors.Wrap(err, "consume id of message container")
}
n, err := b.Int()
if err != nil {
return err
}
for i := 0; i < n; i++ {
var msg Message
if err := msg.Decode(b); err != nil {
return err
}
m.Messages = append(m.Messages, msg)
}
return nil
}
// Message is element of MessageContainer.
type Message struct {
ID int64
SeqNo int
Bytes int
Body []byte
}
// Encode implements bin.Encoder.
func (m *Message) Encode(b *bin.Buffer) error {
if m.Bytes < 0 || m.Bytes > 1024*1024 {
return errors.Errorf("message length %d is invalid", m.Bytes)
}
b.PutLong(m.ID)
b.PutInt(m.SeqNo)
b.PutInt(m.Bytes)
b.Put(m.Body)
return nil
}
// Decode implements bin.Decoder.
func (m *Message) Decode(b *bin.Buffer) error {
{
v, err := b.Long()
if err != nil {
return err
}
m.ID = v
}
{
v, err := b.Int()
if err != nil {
return err
}
m.SeqNo = v
}
{
v, err := b.Int()
if err != nil {
return err
}
m.Bytes = v
}
if m.Bytes < 0 || m.Bytes > 1024*1024 {
return errors.New("message length is too big")
}
m.Body = make([]byte, m.Bytes)
return b.ConsumeN(m.Body, m.Bytes)
}