forked from fl00r/go-tarantool-1.6
-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathsmallbuf.go
More file actions
133 lines (112 loc) · 2.01 KB
/
smallbuf.go
File metadata and controls
133 lines (112 loc) · 2.01 KB
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
package tarantool
import (
"errors"
"io"
)
type smallBuf struct {
b []byte
p int
ptr *[]byte
alloc Allocator
}
func (s *smallBuf) Read(d []byte) (l int, err error) {
l = len(s.b) - s.p
if l == 0 && len(d) > 0 {
return 0, io.EOF
}
if l > len(d) {
l = len(d)
}
copy(d, s.b[s.p:])
s.p += l
return l, nil
}
func (s *smallBuf) ReadByte() (b byte, err error) {
if s.p == len(s.b) {
return 0, io.EOF
}
b = s.b[s.p]
s.p++
return b, nil
}
func (s *smallBuf) UnreadByte() error {
if s.p == 0 {
return errors.New("could not unread")
}
s.p--
return nil
}
func (s *smallBuf) Len() int {
return len(s.b) - s.p
}
func (s *smallBuf) Bytes() []byte {
if len(s.b) > s.p {
return s.b[s.p:]
}
return nil
}
func (s *smallBuf) Offset() int {
return s.p
}
func (s *smallBuf) Seek(offset int) error {
if offset < 0 {
return errors.New("too small offset")
}
if offset > len(s.b) {
return errors.New("too big offset")
}
s.p = offset
return nil
}
func createBuf(a Allocator, size int) smallBuf {
if a == nil {
return smallBuf{b: make([]byte, size)}
}
ptr := a.Get(size)
if ptr == nil {
return smallBuf{b: make([]byte, size)}
}
return smallBuf{b: *ptr, ptr: ptr, alloc: a}
}
func (s *smallBuf) Release() {
if s.alloc != nil && s.ptr != nil {
s.alloc.Put(s.ptr)
}
}
type smallWBuf struct {
b []byte
sum uint
n uint
}
func (s *smallWBuf) Write(b []byte) (int, error) {
s.b = append(s.b, b...)
return len(s.b), nil
}
func (s *smallWBuf) WriteByte(b byte) error {
s.b = append(s.b, b)
return nil
}
func (s *smallWBuf) WriteString(ss string) (int, error) {
s.b = append(s.b, ss...)
return len(ss), nil
}
func (s smallWBuf) Len() int {
return len(s.b)
}
func (s smallWBuf) Cap() int {
return cap(s.b)
}
func (s *smallWBuf) Trunc(n int) {
s.b = s.b[:n]
}
func (s *smallWBuf) Reset() {
s.sum = uint(uint64(s.sum)*15/16) + uint(len(s.b))
if s.n < 16 {
s.n++
}
if cap(s.b) > 1024 && s.sum/s.n < uint(cap(s.b))/4 {
s.b = make([]byte, 0, s.sum/s.n)
} else {
s.b = s.b[:0]
}
}