-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.go
125 lines (102 loc) · 2.22 KB
/
init.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package mux
import (
"io"
"encoding/binary"
)
// Handshake message sent by the client to the server
type Tinit struct {
version int16
headers []Header
}
// Handshake response sent by the server to the client
type Rinit struct {
version int16
headers []Header
}
////////////////////////////
// Tinit Message methods
////////////////////////////
func (t *Tinit) Size() int {
return initSize(t.headers)
}
func (t *Tinit) Type() int8 {
return TinitTpe
}
func (t *Tinit) Encode(writer io.Writer) error {
return encodeInit(writer, t.version, t.headers)
}
////////////////////////////
// Rinit Message methods
////////////////////////////
func (t *Rinit) Size() int {
return initSize(t.headers)
}
func (t *Rinit) Type() int8 {
return TinitTpe
}
func (t *Rinit) Encode(writer io.Writer) error {
return encodeInit(writer, t.version, t.headers)
}
////////////////////////////
// init decoding methods
////////////////////////////
// Requires a limited stream since EOF determines the end of the init frame
func decodeInit(input io.Reader) (version int16, headers []Header, err error) {
err = binary.Read(input, binary.BigEndian, &version)
if err != nil {
return
}
for {
var header Header
header.Key, err = readInt32Slice(input)
if err != nil{
if err == io.EOF { // not really an error
err = nil
}
return
}
header.Value, err = readInt32Slice(input)
if err != nil {
return
}
headers = append(headers, header)
}
}
////////////////////////////
// Helper methods
////////////////////////////
func initSize(headers []Header) int {
acc := 2 // 16 bit version
for _, h := range headers {
acc += 8 // length fields
acc += len(h.Key)
acc += len(h.Value)
}
return acc
}
func encodeInit(writer io.Writer, version int16, headers []Header) (err error) {
err = binary.Write(writer, binary.BigEndian, version)
if err != nil {
return
}
for _, h := range headers {
err = binary.Write(writer, binary.BigEndian, int32(len(h.Key)))
if err != nil {
return
}
_, err = writer.Write(h.Key)
if err != nil {
return
}
err = binary.Write(writer, binary.BigEndian, int32(len(h.Value)))
if err != nil {
return
}
_, err = writer.Write(h.Value)
if err != nil {
return
}
}
// success
return
}