forked from panjf2000/gnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec.go
331 lines (294 loc) · 9.57 KB
/
codec.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// Copyright (c) 2019 Andy Pan
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package gnet
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
errorset "github.com/panjf2000/gnet/errors"
)
// CRLFByte represents a byte of CRLF.
var CRLFByte = byte('\n')
type (
// ICodec is the interface of gnet codec.
ICodec interface {
// Encode encodes frames upon server responses into TCP stream.
Encode(c Conn, buf []byte) ([]byte, error)
// Decode decodes frames from TCP stream via specific implementation.
Decode(c Conn) ([]byte, error)
}
// BuiltInFrameCodec is the built-in codec which will be assigned to gnet server when customized codec is not set up.
BuiltInFrameCodec struct {
}
// LineBasedFrameCodec encodes/decodes line-separated frames into/from TCP stream.
LineBasedFrameCodec struct {
}
// DelimiterBasedFrameCodec encodes/decodes specific-delimiter-separated frames into/from TCP stream.
DelimiterBasedFrameCodec struct {
delimiter byte
}
// FixedLengthFrameCodec encodes/decodes fixed-length-separated frames into/from TCP stream.
FixedLengthFrameCodec struct {
frameLength int
}
// LengthFieldBasedFrameCodec is the refactoring from
// https://github.com/smallnest/goframe/blob/master/length_field_based_frameconn.go, licensed by Apache License 2.0.
// It encodes/decodes frames into/from TCP stream with value of the length field in the message.
LengthFieldBasedFrameCodec struct {
encoderConfig EncoderConfig
decoderConfig DecoderConfig
}
)
// Encode ...
func (cc *BuiltInFrameCodec) Encode(c Conn, buf []byte) ([]byte, error) {
return buf, nil
}
// Decode ...
func (cc *BuiltInFrameCodec) Decode(c Conn) ([]byte, error) {
buf := c.Read()
if len(buf) == 0 {
return nil, nil
}
c.ResetBuffer()
return buf, nil
}
// Encode ...
func (cc *LineBasedFrameCodec) Encode(c Conn, buf []byte) ([]byte, error) {
return append(buf, CRLFByte), nil
}
// Decode ...
func (cc *LineBasedFrameCodec) Decode(c Conn) ([]byte, error) {
buf := c.Read()
idx := bytes.IndexByte(buf, CRLFByte)
if idx == -1 {
return nil, errorset.ErrCRLFNotFound
}
c.ShiftN(idx + 1)
return buf[:idx], nil
}
// NewDelimiterBasedFrameCodec instantiates and returns a codec with a specific delimiter.
func NewDelimiterBasedFrameCodec(delimiter byte) *DelimiterBasedFrameCodec {
return &DelimiterBasedFrameCodec{delimiter}
}
// Encode ...
func (cc *DelimiterBasedFrameCodec) Encode(c Conn, buf []byte) ([]byte, error) {
return append(buf, cc.delimiter), nil
}
// Decode ...
func (cc *DelimiterBasedFrameCodec) Decode(c Conn) ([]byte, error) {
buf := c.Read()
idx := bytes.IndexByte(buf, cc.delimiter)
if idx == -1 {
return nil, errorset.ErrDelimiterNotFound
}
c.ShiftN(idx + 1)
return buf[:idx], nil
}
// NewFixedLengthFrameCodec instantiates and returns a codec with fixed length.
func NewFixedLengthFrameCodec(frameLength int) *FixedLengthFrameCodec {
return &FixedLengthFrameCodec{frameLength}
}
// Encode ...
func (cc *FixedLengthFrameCodec) Encode(c Conn, buf []byte) ([]byte, error) {
if len(buf)%cc.frameLength != 0 {
return nil, errorset.ErrInvalidFixedLength
}
return buf, nil
}
// Decode ...
func (cc *FixedLengthFrameCodec) Decode(c Conn) ([]byte, error) {
size, buf := c.ReadN(cc.frameLength)
if size == 0 {
return nil, errorset.ErrUnexpectedEOF
}
c.ShiftN(size)
return buf, nil
}
// NewLengthFieldBasedFrameCodec instantiates and returns a codec based on the length field.
// It is the go implementation of netty LengthFieldBasedFrameecoder and LengthFieldPrepender.
// you can see javadoc of them to learn more details.
func NewLengthFieldBasedFrameCodec(ec EncoderConfig, dc DecoderConfig) *LengthFieldBasedFrameCodec {
return &LengthFieldBasedFrameCodec{encoderConfig: ec, decoderConfig: dc}
}
// EncoderConfig config for encoder.
type EncoderConfig struct {
// ByteOrder is the ByteOrder of the length field.
ByteOrder binary.ByteOrder
// LengthFieldLength is the length of the length field.
LengthFieldLength int
// LengthAdjustment is the compensation value to add to the value of the length field
LengthAdjustment int
// LengthIncludesLengthFieldLength is true, the length of the prepended length field is added to the value of
// the prepended length field
LengthIncludesLengthFieldLength bool
}
// DecoderConfig config for decoder.
type DecoderConfig struct {
// ByteOrder is the ByteOrder of the length field.
ByteOrder binary.ByteOrder
// LengthFieldOffset is the offset of the length field
LengthFieldOffset int
// LengthFieldLength is the length of the length field
LengthFieldLength int
// LengthAdjustment is the compensation value to add to the value of the length field
LengthAdjustment int
// InitialBytesToStrip is the number of first bytes to strip out from the decoded frame
InitialBytesToStrip int
}
// Encode ...
func (cc *LengthFieldBasedFrameCodec) Encode(c Conn, buf []byte) (out []byte, err error) {
length := len(buf) + cc.encoderConfig.LengthAdjustment
if cc.encoderConfig.LengthIncludesLengthFieldLength {
length += cc.encoderConfig.LengthFieldLength
}
if length < 0 {
return nil, errorset.ErrTooLessLength
}
switch cc.encoderConfig.LengthFieldLength {
case 1:
if length >= 256 {
return nil, fmt.Errorf("length does not fit into a byte: %d", length)
}
out = []byte{byte(length)}
case 2:
if length >= 65536 {
return nil, fmt.Errorf("length does not fit into a short integer: %d", length)
}
out = make([]byte, 2)
cc.encoderConfig.ByteOrder.PutUint16(out, uint16(length))
case 3:
if length >= 16777216 {
return nil, fmt.Errorf("length does not fit into a medium integer: %d", length)
}
out = writeUint24(cc.encoderConfig.ByteOrder, length)
case 4:
out = make([]byte, 4)
cc.encoderConfig.ByteOrder.PutUint32(out, uint32(length))
case 8:
out = make([]byte, 8)
cc.encoderConfig.ByteOrder.PutUint64(out, uint64(length))
default:
return nil, errorset.ErrUnsupportedLength
}
out = append(out, buf...)
return
}
type innerBuffer []byte
func (in *innerBuffer) readN(n int) (buf []byte, err error) {
if n == 0 {
return nil, nil
}
if n < 0 {
return nil, errors.New("negative length is invalid")
} else if n > len(*in) {
return nil, errors.New("exceeding buffer length")
}
buf = (*in)[:n]
*in = (*in)[n:]
return
}
// Decode ...
func (cc *LengthFieldBasedFrameCodec) Decode(c Conn) ([]byte, error) {
var (
in innerBuffer
header []byte
err error
)
in = c.Read()
if cc.decoderConfig.LengthFieldOffset > 0 { // discard header(offset)
header, err = in.readN(cc.decoderConfig.LengthFieldOffset)
if err != nil {
return nil, errorset.ErrUnexpectedEOF
}
}
lenBuf, frameLength, err := cc.getUnadjustedFrameLength(&in)
if err != nil {
return nil, err
}
// real message length
msgLength := int(frameLength) + cc.decoderConfig.LengthAdjustment
msg, err := in.readN(msgLength)
if err != nil {
return nil, errorset.ErrUnexpectedEOF
}
fullMessage := make([]byte, len(header)+len(lenBuf)+msgLength)
copy(fullMessage, header)
copy(fullMessage[len(header):], lenBuf)
copy(fullMessage[len(header)+len(lenBuf):], msg)
c.ShiftN(len(fullMessage))
return fullMessage[cc.decoderConfig.InitialBytesToStrip:], nil
}
func (cc *LengthFieldBasedFrameCodec) getUnadjustedFrameLength(in *innerBuffer) ([]byte, uint64, error) {
switch cc.decoderConfig.LengthFieldLength {
case 1:
b, err := in.readN(1)
if err != nil {
return nil, 0, errorset.ErrUnexpectedEOF
}
return b, uint64(b[0]), nil
case 2:
lenBuf, err := in.readN(2)
if err != nil {
return nil, 0, errorset.ErrUnexpectedEOF
}
return lenBuf, uint64(cc.decoderConfig.ByteOrder.Uint16(lenBuf)), nil
case 3:
lenBuf, err := in.readN(3)
if err != nil {
return nil, 0, errorset.ErrUnexpectedEOF
}
return lenBuf, readUint24(cc.decoderConfig.ByteOrder, lenBuf), nil
case 4:
lenBuf, err := in.readN(4)
if err != nil {
return nil, 0, errorset.ErrUnexpectedEOF
}
return lenBuf, uint64(cc.decoderConfig.ByteOrder.Uint32(lenBuf)), nil
case 8:
lenBuf, err := in.readN(8)
if err != nil {
return nil, 0, errorset.ErrUnexpectedEOF
}
return lenBuf, cc.decoderConfig.ByteOrder.Uint64(lenBuf), nil
default:
return nil, 0, errorset.ErrUnsupportedLength
}
}
func readUint24(byteOrder binary.ByteOrder, b []byte) uint64 {
_ = b[2]
if byteOrder == binary.LittleEndian {
return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16
}
return uint64(b[2]) | uint64(b[1])<<8 | uint64(b[0])<<16
}
func writeUint24(byteOrder binary.ByteOrder, v int) []byte {
b := make([]byte, 3)
if byteOrder == binary.LittleEndian {
b[0] = byte(v)
b[1] = byte(v >> 8)
b[2] = byte(v >> 16)
} else {
b[2] = byte(v)
b[1] = byte(v >> 8)
b[0] = byte(v >> 16)
}
return b
}