OSDN Git Service

Update Go library to r60.
[pf3gnuchains/gcc-fork.git] / libgo / go / bytes / buffer.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package bytes
6
7 // Simple byte buffer for marshaling data.
8
9 import (
10         "io"
11         "os"
12         "utf8"
13 )
14
15 // A Buffer is a variable-sized buffer of bytes with Read and Write methods.
16 // The zero value for Buffer is an empty buffer ready to use.
17 type Buffer struct {
18         buf       []byte            // contents are the bytes buf[off : len(buf)]
19         off       int               // read at &buf[off], write at &buf[len(buf)]
20         runeBytes [utf8.UTFMax]byte // avoid allocation of slice on each WriteByte or Rune
21         bootstrap [64]byte          // memory to hold first slice; helps small buffers (Printf) avoid allocation.
22         lastRead  readOp            // last read operation, so that Unread* can work correctly.
23 }
24
25 // The readOp constants describe the last action performed on
26 // the buffer, so that UnreadRune and UnreadByte can
27 // check for invalid usage.
28 type readOp int
29
30 const (
31         opInvalid  readOp = iota // Non-read operation.
32         opReadRune               // Read rune.
33         opRead                   // Any other read operation.
34 )
35
36 // Bytes returns a slice of the contents of the unread portion of the buffer;
37 // len(b.Bytes()) == b.Len().  If the caller changes the contents of the
38 // returned slice, the contents of the buffer will change provided there
39 // are no intervening method calls on the Buffer.
40 func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }
41
42 // String returns the contents of the unread portion of the buffer
43 // as a string.  If the Buffer is a nil pointer, it returns "<nil>".
44 func (b *Buffer) String() string {
45         if b == nil {
46                 // Special case, useful in debugging.
47                 return "<nil>"
48         }
49         return string(b.buf[b.off:])
50 }
51
52 // Len returns the number of bytes of the unread portion of the buffer;
53 // b.Len() == len(b.Bytes()).
54 func (b *Buffer) Len() int { return len(b.buf) - b.off }
55
56 // Truncate discards all but the first n unread bytes from the buffer.
57 // It is an error to call b.Truncate(n) with n > b.Len().
58 func (b *Buffer) Truncate(n int) {
59         b.lastRead = opInvalid
60         if n == 0 {
61                 // Reuse buffer space.
62                 b.off = 0
63         }
64         b.buf = b.buf[0 : b.off+n]
65 }
66
67 // Reset resets the buffer so it has no content.
68 // b.Reset() is the same as b.Truncate(0).
69 func (b *Buffer) Reset() { b.Truncate(0) }
70
71 // Grow buffer to guarantee space for n more bytes.
72 // Return index where bytes should be written.
73 func (b *Buffer) grow(n int) int {
74         m := b.Len()
75         // If buffer is empty, reset to recover space.
76         if m == 0 && b.off != 0 {
77                 b.Truncate(0)
78         }
79         if len(b.buf)+n > cap(b.buf) {
80                 var buf []byte
81                 if b.buf == nil && n <= len(b.bootstrap) {
82                         buf = b.bootstrap[0:]
83                 } else {
84                         // not enough space anywhere
85                         buf = make([]byte, 2*cap(b.buf)+n)
86                         copy(buf, b.buf[b.off:])
87                 }
88                 b.buf = buf
89                 b.off = 0
90         }
91         b.buf = b.buf[0 : b.off+m+n]
92         return b.off + m
93 }
94
95 // Write appends the contents of p to the buffer.  The return
96 // value n is the length of p; err is always nil.
97 func (b *Buffer) Write(p []byte) (n int, err os.Error) {
98         b.lastRead = opInvalid
99         m := b.grow(len(p))
100         copy(b.buf[m:], p)
101         return len(p), nil
102 }
103
104 // WriteString appends the contents of s to the buffer.  The return
105 // value n is the length of s; err is always nil.
106 func (b *Buffer) WriteString(s string) (n int, err os.Error) {
107         b.lastRead = opInvalid
108         m := b.grow(len(s))
109         return copy(b.buf[m:], s), nil
110 }
111
112 // MinRead is the minimum slice size passed to a Read call by
113 // Buffer.ReadFrom.  As long as the Buffer has at least MinRead bytes beyond
114 // what is required to hold the contents of r, ReadFrom will not grow the
115 // underlying buffer.
116 const MinRead = 512
117
118 // ReadFrom reads data from r until EOF and appends it to the buffer.
119 // The return value n is the number of bytes read.
120 // Any error except os.EOF encountered during the read
121 // is also returned.
122 func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) {
123         b.lastRead = opInvalid
124         // If buffer is empty, reset to recover space.
125         if b.off >= len(b.buf) {
126                 b.Truncate(0)
127         }
128         for {
129                 if cap(b.buf)-len(b.buf) < MinRead {
130                         var newBuf []byte
131                         // can we get space without allocation?
132                         if b.off+cap(b.buf)-len(b.buf) >= MinRead {
133                                 // reuse beginning of buffer
134                                 newBuf = b.buf[0 : len(b.buf)-b.off]
135                         } else {
136                                 // not enough space at end; put space on end
137                                 newBuf = make([]byte, len(b.buf)-b.off, 2*(cap(b.buf)-b.off)+MinRead)
138                         }
139                         copy(newBuf, b.buf[b.off:])
140                         b.buf = newBuf
141                         b.off = 0
142                 }
143                 m, e := r.Read(b.buf[len(b.buf):cap(b.buf)])
144                 b.buf = b.buf[0 : len(b.buf)+m]
145                 n += int64(m)
146                 if e == os.EOF {
147                         break
148                 }
149                 if e != nil {
150                         return n, e
151                 }
152         }
153         return n, nil // err is EOF, so return nil explicitly
154 }
155
156 // WriteTo writes data to w until the buffer is drained or an error
157 // occurs. The return value n is the number of bytes written; it always
158 // fits into an int, but it is int64 to match the io.WriterTo interface.
159 // Any error encountered during the write is also returned.
160 func (b *Buffer) WriteTo(w io.Writer) (n int64, err os.Error) {
161         b.lastRead = opInvalid
162         if b.off < len(b.buf) {
163                 m, e := w.Write(b.buf[b.off:])
164                 b.off += m
165                 n = int64(m)
166                 if e != nil {
167                         return n, e
168                 }
169                 // otherwise all bytes were written, by definition of
170                 // Write method in io.Writer
171         }
172         // Buffer is now empty; reset.
173         b.Truncate(0)
174         return
175 }
176
177 // WriteByte appends the byte c to the buffer.
178 // The returned error is always nil, but is included
179 // to match bufio.Writer's WriteByte.
180 func (b *Buffer) WriteByte(c byte) os.Error {
181         b.lastRead = opInvalid
182         m := b.grow(1)
183         b.buf[m] = c
184         return nil
185 }
186
187 // WriteRune appends the UTF-8 encoding of Unicode
188 // code point r to the buffer, returning its length and
189 // an error, which is always nil but is included
190 // to match bufio.Writer's WriteRune.
191 func (b *Buffer) WriteRune(r int) (n int, err os.Error) {
192         if r < utf8.RuneSelf {
193                 b.WriteByte(byte(r))
194                 return 1, nil
195         }
196         n = utf8.EncodeRune(b.runeBytes[0:], r)
197         b.Write(b.runeBytes[0:n])
198         return n, nil
199 }
200
201 // Read reads the next len(p) bytes from the buffer or until the buffer
202 // is drained.  The return value n is the number of bytes read.  If the
203 // buffer has no data to return, err is os.EOF even if len(p) is zero;
204 // otherwise it is nil.
205 func (b *Buffer) Read(p []byte) (n int, err os.Error) {
206         b.lastRead = opInvalid
207         if b.off >= len(b.buf) {
208                 // Buffer is empty, reset to recover space.
209                 b.Truncate(0)
210                 return 0, os.EOF
211         }
212         n = copy(p, b.buf[b.off:])
213         b.off += n
214         if n > 0 {
215                 b.lastRead = opRead
216         }
217         return
218 }
219
220 // Next returns a slice containing the next n bytes from the buffer,
221 // advancing the buffer as if the bytes had been returned by Read.
222 // If there are fewer than n bytes in the buffer, Next returns the entire buffer.
223 // The slice is only valid until the next call to a read or write method.
224 func (b *Buffer) Next(n int) []byte {
225         b.lastRead = opInvalid
226         m := b.Len()
227         if n > m {
228                 n = m
229         }
230         data := b.buf[b.off : b.off+n]
231         b.off += n
232         if n > 0 {
233                 b.lastRead = opRead
234         }
235         return data
236 }
237
238 // ReadByte reads and returns the next byte from the buffer.
239 // If no byte is available, it returns error os.EOF.
240 func (b *Buffer) ReadByte() (c byte, err os.Error) {
241         b.lastRead = opInvalid
242         if b.off >= len(b.buf) {
243                 // Buffer is empty, reset to recover space.
244                 b.Truncate(0)
245                 return 0, os.EOF
246         }
247         c = b.buf[b.off]
248         b.off++
249         b.lastRead = opRead
250         return c, nil
251 }
252
253 // ReadRune reads and returns the next UTF-8-encoded
254 // Unicode code point from the buffer.
255 // If no bytes are available, the error returned is os.EOF.
256 // If the bytes are an erroneous UTF-8 encoding, it
257 // consumes one byte and returns U+FFFD, 1.
258 func (b *Buffer) ReadRune() (r int, size int, err os.Error) {
259         b.lastRead = opInvalid
260         if b.off >= len(b.buf) {
261                 // Buffer is empty, reset to recover space.
262                 b.Truncate(0)
263                 return 0, 0, os.EOF
264         }
265         b.lastRead = opReadRune
266         c := b.buf[b.off]
267         if c < utf8.RuneSelf {
268                 b.off++
269                 return int(c), 1, nil
270         }
271         r, n := utf8.DecodeRune(b.buf[b.off:])
272         b.off += n
273         return r, n, nil
274 }
275
276 // UnreadRune unreads the last rune returned by ReadRune.
277 // If the most recent read or write operation on the buffer was
278 // not a ReadRune, UnreadRune returns an error.  (In this regard
279 // it is stricter than UnreadByte, which will unread the last byte
280 // from any read operation.)
281 func (b *Buffer) UnreadRune() os.Error {
282         if b.lastRead != opReadRune {
283                 return os.NewError("bytes.Buffer: UnreadRune: previous operation was not ReadRune")
284         }
285         b.lastRead = opInvalid
286         if b.off > 0 {
287                 _, n := utf8.DecodeLastRune(b.buf[0:b.off])
288                 b.off -= n
289         }
290         return nil
291 }
292
293 // UnreadByte unreads the last byte returned by the most recent
294 // read operation.  If write has happened since the last read, UnreadByte
295 // returns an error.
296 func (b *Buffer) UnreadByte() os.Error {
297         if b.lastRead != opReadRune && b.lastRead != opRead {
298                 return os.NewError("bytes.Buffer: UnreadByte: previous operation was not a read")
299         }
300         b.lastRead = opInvalid
301         if b.off > 0 {
302                 b.off--
303         }
304         return nil
305 }
306
307 // ReadBytes reads until the first occurrence of delim in the input,
308 // returning a slice containing the data up to and including the delimiter.
309 // If ReadBytes encounters an error before finding a delimiter,
310 // it returns the data read before the error and the error itself (often os.EOF).
311 // ReadBytes returns err != nil if and only if the returned data does not end in
312 // delim.
313 func (b *Buffer) ReadBytes(delim byte) (line []byte, err os.Error) {
314         i := IndexByte(b.buf[b.off:], delim)
315         size := i + 1
316         if i < 0 {
317                 size = len(b.buf) - b.off
318                 err = os.EOF
319         }
320         line = make([]byte, size)
321         copy(line, b.buf[b.off:])
322         b.off += size
323         return
324 }
325
326 // ReadString reads until the first occurrence of delim in the input,
327 // returning a string containing the data up to and including the delimiter.
328 // If ReadString encounters an error before finding a delimiter,
329 // it returns the data read before the error and the error itself (often os.EOF).
330 // ReadString returns err != nil if and only if the returned data does not end
331 // in delim.
332 func (b *Buffer) ReadString(delim byte) (line string, err os.Error) {
333         bytes, err := b.ReadBytes(delim)
334         return string(bytes), err
335 }
336
337 // NewBuffer creates and initializes a new Buffer using buf as its initial
338 // contents.  It is intended to prepare a Buffer to read existing data.  It
339 // can also be used to size the internal buffer for writing.  To do that,
340 // buf should have the desired capacity but a length of zero.
341 func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }
342
343 // NewBufferString creates and initializes a new Buffer using string s as its
344 // initial contents.  It is intended to prepare a buffer to read an existing
345 // string.
346 func NewBufferString(s string) *Buffer {
347         return &Buffer{buf: []byte(s)}
348 }