-
-
Notifications
You must be signed in to change notification settings - Fork 118
/
proto.go
63 lines (51 loc) · 1.24 KB
/
proto.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 exchange
import (
"context"
"github.com/gotd/td/clock"
"golang.org/x/xerrors"
"github.com/gotd/td/bin"
"github.com/gotd/td/internal/proto"
"github.com/gotd/td/transport"
)
type unencryptedWriter struct {
clock clock.Clock
conn transport.Conn
input proto.MessageType
output proto.MessageType
}
func (w unencryptedWriter) writeUnencrypted(ctx context.Context, b *bin.Buffer, data bin.Encoder) error {
b.Reset()
if err := data.Encode(b); err != nil {
return err
}
msg := proto.UnencryptedMessage{
MessageID: int64(proto.NewMessageID(w.clock.Now(), w.output)),
MessageData: b.Copy(),
}
b.Reset()
if err := msg.Encode(b); err != nil {
return err
}
return w.conn.Send(ctx, b)
}
func (w unencryptedWriter) readUnencrypted(ctx context.Context, b *bin.Buffer, data bin.Decoder) error {
b.Reset()
if err := w.conn.Recv(ctx, b); err != nil {
return err
}
var msg proto.UnencryptedMessage
if err := msg.Decode(b); err != nil {
return err
}
if err := w.checkMsgID(msg.MessageID); err != nil {
return err
}
b.ResetTo(msg.MessageData)
return data.Decode(b)
}
func (w unencryptedWriter) checkMsgID(id int64) error {
if proto.MessageID(id).Type() != w.input {
return xerrors.New("bad msg type")
}
return nil
}