source: code/trunk/vendor/github.com/valyala/bytebufferpool/bytebuffer.go@ 145

Last change on this file since 145 was 145, checked in by Izuru Yakumo, 22 months ago

Updated the Makefile and vendored depedencies

Signed-off-by: Izuru Yakumo <yakumo.izuru@…>

File size: 2.3 KB
Line 
1package bytebufferpool
2
3import "io"
4
5// ByteBuffer provides byte buffer, which can be used for minimizing
6// memory allocations.
7//
8// ByteBuffer may be used with functions appending data to the given []byte
9// slice. See example code for details.
10//
11// Use Get for obtaining an empty byte buffer.
12type ByteBuffer struct {
13
14 // B is a byte buffer to use in append-like workloads.
15 // See example code for details.
16 B []byte
17}
18
19// Len returns the size of the byte buffer.
20func (b *ByteBuffer) Len() int {
21 return len(b.B)
22}
23
24// ReadFrom implements io.ReaderFrom.
25//
26// The function appends all the data read from r to b.
27func (b *ByteBuffer) ReadFrom(r io.Reader) (int64, error) {
28 p := b.B
29 nStart := int64(len(p))
30 nMax := int64(cap(p))
31 n := nStart
32 if nMax == 0 {
33 nMax = 64
34 p = make([]byte, nMax)
35 } else {
36 p = p[:nMax]
37 }
38 for {
39 if n == nMax {
40 nMax *= 2
41 bNew := make([]byte, nMax)
42 copy(bNew, p)
43 p = bNew
44 }
45 nn, err := r.Read(p[n:])
46 n += int64(nn)
47 if err != nil {
48 b.B = p[:n]
49 n -= nStart
50 if err == io.EOF {
51 return n, nil
52 }
53 return n, err
54 }
55 }
56}
57
58// WriteTo implements io.WriterTo.
59func (b *ByteBuffer) WriteTo(w io.Writer) (int64, error) {
60 n, err := w.Write(b.B)
61 return int64(n), err
62}
63
64// Bytes returns b.B, i.e. all the bytes accumulated in the buffer.
65//
66// The purpose of this function is bytes.Buffer compatibility.
67func (b *ByteBuffer) Bytes() []byte {
68 return b.B
69}
70
71// Write implements io.Writer - it appends p to ByteBuffer.B
72func (b *ByteBuffer) Write(p []byte) (int, error) {
73 b.B = append(b.B, p...)
74 return len(p), nil
75}
76
77// WriteByte appends the byte c to the buffer.
78//
79// The purpose of this function is bytes.Buffer compatibility.
80//
81// The function always returns nil.
82func (b *ByteBuffer) WriteByte(c byte) error {
83 b.B = append(b.B, c)
84 return nil
85}
86
87// WriteString appends s to ByteBuffer.B.
88func (b *ByteBuffer) WriteString(s string) (int, error) {
89 b.B = append(b.B, s...)
90 return len(s), nil
91}
92
93// Set sets ByteBuffer.B to p.
94func (b *ByteBuffer) Set(p []byte) {
95 b.B = append(b.B[:0], p...)
96}
97
98// SetString sets ByteBuffer.B to s.
99func (b *ByteBuffer) SetString(s string) {
100 b.B = append(b.B[:0], s...)
101}
102
103// String returns string representation of ByteBuffer.B.
104func (b *ByteBuffer) String() string {
105 return string(b.B)
106}
107
108// Reset makes ByteBuffer.B empty.
109func (b *ByteBuffer) Reset() {
110 b.B = b.B[:0]
111}
Note: See TracBrowser for help on using the repository browser.