-
Notifications
You must be signed in to change notification settings - Fork 0
/
requestStream.go
89 lines (80 loc) · 1.68 KB
/
requestStream.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
package fasthttp
import (
"bufio"
"bytes"
"fmt"
"io"
"sync"
"github.com/valyala/bytebufferpool"
)
type requestStream struct {
prefetchedBytes *bytes.Reader
reader *bufio.Reader
n int
contentLength int
}
func (rs *requestStream) Read(p []byte) (int, error) {
if rs.contentLength == -1 {
p = p[:0]
strCRLFLen := len(strCRLF)
chunkSize, err := parseChunkSize(rs.reader)
if err != nil {
return len(p), err
}
p, err = appendBodyFixedSize(rs.reader, p, chunkSize+strCRLFLen)
if err != nil {
return len(p), err
}
if !bytes.Equal(p[len(p)-strCRLFLen:], strCRLF) {
return len(p), ErrBrokenChunk{
error: fmt.Errorf("cannot find crlf at the end of chunk"),
}
}
p = p[:len(p)-strCRLFLen]
if chunkSize == 0 {
return len(p), io.EOF
}
return len(p), nil
}
if rs.n == rs.contentLength {
return 0, io.EOF
}
var n int
var err error
if int(rs.prefetchedBytes.Size()) > rs.n {
n, err := rs.prefetchedBytes.Read(p)
rs.n += n
if n == rs.contentLength {
return n, io.EOF
}
return n, err
} else {
n, err = rs.reader.Read(p)
rs.n += n
if err != nil {
return n, err
}
}
if rs.n == rs.contentLength {
err = io.EOF
}
return n, err
}
func acquireRequestStream(b *bytebufferpool.ByteBuffer, r *bufio.Reader, contentLength int) *requestStream {
rs := requestStreamPool.Get().(*requestStream)
rs.prefetchedBytes = bytes.NewReader(b.B)
rs.reader = r
rs.contentLength = contentLength
return rs
}
func releaseRequestStream(rs *requestStream) {
rs.prefetchedBytes = nil
rs.n = 0
rs.reader = nil
requestStreamPool.Put(rs)
}
var requestStreamPool = sync.Pool{
New: func() interface{} {
return &requestStream{}
},
}