-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathproto.go
64 lines (56 loc) · 1.49 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
64
package nq
import (
"encoding/binary"
"errors"
"io"
)
// Binary protocol
// ~~~~~~~~~~~~~~~
//
// +=======...=+===============... =+
// | size ... | payload ... |
// |UVarInt... | (size) octets ... |
// +=======...=+===============... =+
// | | |
// |<-[1..10]->|<- (size) ...->|
//
// * size of the payload -- unsigned 64bit varint, [1..10] octets. Practically, size is limited by the MaxPayload value.
// * payload: arbitrary bytes, [0 .. MaxPayload] bytes.
var (
// MaxPayload prevents receiving side from DoS atack due to allocating too much RAM
MaxPayload = 10 * 1024 * 1024 // 10Mb ought to be enough for anybody
// ErrTooBig indicates that payload exceeds the limit
ErrTooBig = errors.New("nanoq: payload exceeds the limit")
)
const maxHeaderLen = binary.MaxVarintLen64
type encoder struct {
scratchpad [maxHeaderLen]byte
}
func (e *encoder) EncodeTo(w io.Writer, p []byte) error {
size := len(p)
if size > MaxPayload {
return ErrTooBig
}
// write size header
n := binary.PutUvarint(e.scratchpad[:], uint64(size))
if _, err := w.Write(e.scratchpad[:n]); err != nil {
return err
}
// write payload
if _, err := w.Write(p); err != nil {
return err
}
return nil
}
// decodeSize returns the size of a payload in bytes
func decodeSize(r io.ByteReader) (int, error) {
// header: payload size
size, err := binary.ReadUvarint(r)
if err != nil {
return 0, err
}
if size > uint64(MaxPayload) {
return 0, ErrTooBig
}
return int(size), nil
}