forked from mosn/mosn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iobuffer.go
491 lines (392 loc) · 8.37 KB
/
iobuffer.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package buffer
import (
"errors"
"io"
"net"
"time"
"sync/atomic"
"mosn.io/mosn/pkg/types"
)
const MinRead = 1 << 9
const MaxRead = 1 << 17
const ResetOffMark = -1
const DefaultSize = 1 << 4
var nullByte []byte
var (
EOF = errors.New("EOF")
ErrTooLarge = errors.New("io buffer: too large")
ErrNegativeCount = errors.New("io buffer: negative count")
ErrInvalidWriteCount = errors.New("io buffer: invalid write count")
ConnReadTimeout = types.DefaultConnReadTimeout
)
// IoBuffer
type IoBuffer struct {
buf []byte // contents: buf[off : len(buf)]
off int // read from &buf[off], write to &buf[len(buf)]
offMark int
count int32
eof bool
b *[]byte
}
func (b *IoBuffer) Read(p []byte) (n int, err error) {
if b.off >= len(b.buf) {
b.Reset()
if len(p) == 0 {
return
}
return 0, io.EOF
}
n = copy(p, b.buf[b.off:])
b.off += n
return
}
func (b *IoBuffer) ReadOnce(r io.Reader) (n int64, e error) {
var (
m int
zeroTime time.Time
conn net.Conn
loop, ok, first = true, true, true
)
if conn, ok = r.(net.Conn); !ok {
loop = false
}
if b.off >= len(b.buf) {
b.Reset()
}
if b.off > 0 && len(b.buf)-b.off < 4*MinRead {
b.copy(0)
}
if cap(b.buf) == len(b.buf) {
b.copy(MinRead)
}
for {
if first == false {
if free := cap(b.buf) - len(b.buf); free < MinRead {
// not enough space at end
if b.off+free < MinRead {
// not enough space using beginning of buffer;
// double buffer capacity
b.copy(MinRead)
} else {
b.copy(0)
}
}
}
l := cap(b.buf) - len(b.buf)
if conn != nil {
if first {
// TODO: support configure
conn.SetReadDeadline(time.Now().Add(ConnReadTimeout))
} else {
conn.SetReadDeadline(time.Now().Add(10 * time.Millisecond))
}
m, e = r.Read(b.buf[len(b.buf):cap(b.buf)])
// Reset read deadline
conn.SetReadDeadline(zeroTime)
} else {
m, e = r.Read(b.buf[len(b.buf):cap(b.buf)])
}
if m > 0 {
b.buf = b.buf[0 : len(b.buf)+m]
n += int64(m)
}
if e != nil {
if te, ok := e.(net.Error); ok && te.Timeout() && !first {
return n, nil
}
return n, e
}
if l != m {
loop = false
}
if n > MaxRead {
loop = false
}
if !loop {
break
}
first = false
}
return n, nil
}
func (b *IoBuffer) ReadFrom(r io.Reader) (n int64, err error) {
if b.off >= len(b.buf) {
b.Reset()
}
for {
if free := cap(b.buf) - len(b.buf); free < MinRead {
// not enough space at end
if b.off+free < MinRead {
// not enough space using beginning of buffer;
// double buffer capacity
b.copy(MinRead)
} else {
b.copy(0)
}
}
m, e := r.Read(b.buf[len(b.buf):cap(b.buf)])
b.buf = b.buf[0 : len(b.buf)+m]
n += int64(m)
if e == io.EOF {
break
}
if m == 0 {
break
}
if e != nil {
return n, e
}
}
return
}
func (b *IoBuffer) Write(p []byte) (n int, err error) {
m, ok := b.tryGrowByReslice(len(p))
if !ok {
m = b.grow(len(p))
}
return copy(b.buf[m:], p), nil
}
func (b *IoBuffer) WriteString(s string) (n int, err error) {
m, ok := b.tryGrowByReslice(len(s))
if !ok {
m = b.grow(len(s))
}
return copy(b.buf[m:], s), nil
}
func (b *IoBuffer) tryGrowByReslice(n int) (int, bool) {
if l := len(b.buf); l+n <= cap(b.buf) {
b.buf = b.buf[:l+n]
return l, true
}
return 0, false
}
func (b *IoBuffer) grow(n int) int {
m := b.Len()
// If buffer is empty, reset to recover space.
if m == 0 && b.off != 0 {
b.Reset()
}
// Try to grow by means of a reslice.
if i, ok := b.tryGrowByReslice(n); ok {
return i
}
if m+n <= cap(b.buf)/2 {
// We can slide things down instead of allocating a new
// slice. We only need m+n <= cap(b.buf) to slide, but
// we instead let capacity get twice as large so we
// don't spend all our time copying.
b.copy(0)
} else {
// Not enough space anywhere, we need to allocate.
b.copy(n)
}
// Restore b.off and len(b.buf).
b.off = 0
b.buf = b.buf[:m+n]
return m
}
func (b *IoBuffer) WriteTo(w io.Writer) (n int64, err error) {
for b.off < len(b.buf) {
nBytes := b.Len()
m, e := w.Write(b.buf[b.off:])
if m > nBytes {
panic(ErrInvalidWriteCount)
}
b.off += m
n += int64(m)
if e != nil {
return n, e
}
if m == 0 || m == nBytes {
return n, nil
}
}
return
}
func (b *IoBuffer) Append(data []byte) error {
if b.off >= len(b.buf) {
b.Reset()
}
dataLen := len(data)
if free := cap(b.buf) - len(b.buf); free < dataLen {
// not enough space at end
if b.off+free < dataLen {
// not enough space using beginning of buffer;
// double buffer capacity
b.copy(dataLen)
} else {
b.copy(0)
}
}
m := copy(b.buf[len(b.buf):len(b.buf)+dataLen], data)
b.buf = b.buf[0 : len(b.buf)+m]
return nil
}
func (b *IoBuffer) AppendByte(data byte) error {
return b.Append([]byte{data})
}
func (b *IoBuffer) Peek(n int) []byte {
if len(b.buf)-b.off < n {
return nil
}
return b.buf[b.off : b.off+n]
}
func (b *IoBuffer) Mark() {
b.offMark = b.off
}
func (b *IoBuffer) Restore() {
if b.offMark != ResetOffMark {
b.off = b.offMark
b.offMark = ResetOffMark
}
}
func (b *IoBuffer) Bytes() []byte {
return b.buf[b.off:]
}
func (b *IoBuffer) Cut(offset int) types.IoBuffer {
if b.off+offset > len(b.buf) {
return nil
}
buf := make([]byte, offset)
copy(buf, b.buf[b.off:b.off+offset])
b.off += offset
b.offMark = ResetOffMark
return &IoBuffer{
buf: buf,
off: 0,
}
}
func (b *IoBuffer) Drain(offset int) {
if b.off+offset > len(b.buf) {
return
}
b.off += offset
b.offMark = ResetOffMark
}
func (b *IoBuffer) String() string {
return string(b.buf[b.off:])
}
func (b *IoBuffer) Len() int {
return len(b.buf) - b.off
}
func (b *IoBuffer) Cap() int {
return cap(b.buf)
}
func (b *IoBuffer) Reset() {
b.buf = b.buf[:0]
b.off = 0
b.offMark = ResetOffMark
b.eof = false
}
func (b *IoBuffer) available() int {
return len(b.buf) - b.off
}
func (b *IoBuffer) Clone() types.IoBuffer {
buf := GetIoBuffer(b.Len())
buf.Write(b.Bytes())
buf.SetEOF(b.EOF())
return buf
}
func (b *IoBuffer) Free() {
b.Reset()
b.giveSlice()
}
func (b *IoBuffer) Alloc(size int) {
if b.buf != nil {
b.Free()
}
if size <= 0 {
size = DefaultSize
}
b.b = b.makeSlice(size)
b.buf = *b.b
b.buf = b.buf[:0]
}
func (b *IoBuffer) Count(count int32) int32 {
return atomic.AddInt32(&b.count, count)
}
func (b *IoBuffer) EOF() bool {
return b.eof
}
func (b *IoBuffer) SetEOF(eof bool) {
b.eof = eof
}
func (b *IoBuffer) copy(expand int) {
var newBuf []byte
var bufp *[]byte
if expand > 0 {
bufp = b.makeSlice(2*cap(b.buf) + expand)
newBuf = *bufp
copy(newBuf, b.buf[b.off:])
PutBytes(b.b)
b.b = bufp
} else {
newBuf = b.buf
copy(newBuf, b.buf[b.off:])
}
b.buf = newBuf[:len(b.buf)-b.off]
b.off = 0
}
func (b *IoBuffer) makeSlice(n int) *[]byte {
return GetBytes(n)
}
func (b *IoBuffer) giveSlice() {
if b.b != nil {
PutBytes(b.b)
b.b = nil
b.buf = nullByte
}
}
func NewIoBuffer(capacity int) types.IoBuffer {
buffer := &IoBuffer{
offMark: ResetOffMark,
count: 1,
}
if capacity <= 0 {
capacity = DefaultSize
}
buffer.b = GetBytes(capacity)
buffer.buf = (*buffer.b)[:0]
return buffer
}
func NewIoBufferString(s string) types.IoBuffer {
if s == "" {
return NewIoBuffer(0)
}
return &IoBuffer{
buf: []byte(s),
offMark: ResetOffMark,
count: 1,
}
}
func NewIoBufferBytes(bytes []byte) types.IoBuffer {
if bytes == nil {
return NewIoBuffer(0)
}
return &IoBuffer{
buf: bytes,
offMark: ResetOffMark,
count: 1,
}
}
func NewIoBufferEOF() types.IoBuffer {
buf := NewIoBuffer(0)
buf.SetEOF(true)
return buf
}