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.
5 // This package implements buffered I/O. It wraps an io.Reader or io.Writer
6 // object, creating another object (Reader or Writer) that also implements
7 // the interface but provides buffering and some help for textual I/O.
23 // Errors introduced by this package.
29 ErrInvalidUnreadByte os.Error = &Error{"bufio: invalid use of UnreadByte"}
30 ErrInvalidUnreadRune os.Error = &Error{"bufio: invalid use of UnreadRune"}
31 ErrBufferFull os.Error = &Error{"bufio: buffer full"}
32 ErrNegativeCount os.Error = &Error{"bufio: negative count"}
33 errInternal os.Error = &Error{"bufio: internal error"}
36 // BufSizeError is the error representing an invalid buffer size.
39 func (b BufSizeError) String() string {
40 return "bufio: bad buffer size " + strconv.Itoa(int(b))
46 // Reader implements buffering for an io.Reader object.
56 // NewReaderSize creates a new Reader whose buffer has the specified size,
57 // which must be greater than zero. If the argument io.Reader is already a
58 // Reader with large enough size, it returns the underlying Reader.
59 // It returns the Reader and any error.
60 func NewReaderSize(rd io.Reader, size int) (*Reader, os.Error) {
62 return nil, BufSizeError(size)
64 // Is it already a Reader?
66 if ok && len(b.buf) >= size {
70 b.buf = make([]byte, size)
77 // NewReader returns a new Reader whose buffer has the default size.
78 func NewReader(rd io.Reader) *Reader {
79 b, err := NewReaderSize(rd, defaultBufSize)
81 // cannot happen - defaultBufSize is a valid size
87 // fill reads a new chunk into the buffer.
88 func (b *Reader) fill() {
89 // Slide existing data to beginning.
91 copy(b.buf, b.buf[b.r:b.w])
97 n, e := b.rd.Read(b.buf[b.w:])
104 // Peek returns the next n bytes without advancing the reader. The bytes stop
105 // being valid at the next read call. If Peek returns fewer than n bytes, it
106 // also returns an error explaining why the read is short. The error is
107 // ErrBufferFull if n is larger than b's buffer size.
108 func (b *Reader) Peek(n int) ([]byte, os.Error) {
110 return nil, ErrNegativeCount
113 return nil, ErrBufferFull
115 for b.w-b.r < n && b.err == nil {
123 if m < n && err == nil {
126 return b.buf[b.r : b.r+m], err
129 // Read reads data into p.
130 // It returns the number of bytes read into p.
131 // If nn < len(p), also returns an error explaining
132 // why the read is short. At EOF, the count will be
133 // zero and err will be os.EOF.
134 func (b *Reader) Read(p []byte) (nn int, err os.Error) {
142 if len(p) >= len(b.buf) {
143 // Large read, empty buffer.
144 // Read directly into p to avoid copy.
145 n, b.err = b.rd.Read(p)
147 b.lastByte = int(p[n-1])
160 copy(p[0:n], b.buf[b.r:])
163 b.lastByte = int(b.buf[b.r-1])
170 // ReadByte reads and returns a single byte.
171 // If no byte is available, returns an error.
172 func (b *Reader) ReadByte() (c byte, err os.Error) {
186 // UnreadByte unreads the last byte. Only the most recently read byte can be unread.
187 func (b *Reader) UnreadByte() os.Error {
189 if b.r == b.w && b.lastByte >= 0 {
192 b.buf[0] = byte(b.lastByte)
197 return ErrInvalidUnreadByte
204 // ReadRune reads a single UTF-8 encoded Unicode character and returns the
205 // rune and its size in bytes.
206 func (b *Reader) ReadRune() (rune int, size int, err os.Error) {
207 for b.r+utf8.UTFMax > b.w && !utf8.FullRune(b.buf[b.r:b.w]) && b.err == nil {
214 rune, size = int(b.buf[b.r]), 1
216 rune, size = utf8.DecodeRune(b.buf[b.r:b.w])
219 b.lastByte = int(b.buf[b.r-1])
220 b.lastRuneSize = size
221 return rune, size, nil
224 // UnreadRune unreads the last rune. If the most recent read operation on
225 // the buffer was not a ReadRune, UnreadRune returns an error. (In this
226 // regard it is stricter than UnreadByte, which will unread the last byte
227 // from any read operation.)
228 func (b *Reader) UnreadRune() os.Error {
229 if b.lastRuneSize < 0 || b.r == 0 {
230 return ErrInvalidUnreadRune
232 b.r -= b.lastRuneSize
238 // Buffered returns the number of bytes that can be read from the current buffer.
239 func (b *Reader) Buffered() int { return b.w - b.r }
241 // ReadSlice reads until the first occurrence of delim in the input,
242 // returning a slice pointing at the bytes in the buffer.
243 // The bytes stop being valid at the next read call.
244 // If ReadSlice encounters an error before finding a delimiter,
245 // it returns all the data in the buffer and the error itself (often os.EOF).
246 // ReadSlice fails with error ErrBufferFull if the buffer fills without a delim.
247 // Because the data returned from ReadSlice will be overwritten
248 // by the next I/O operation, most clients should use
249 // ReadBytes or ReadString instead.
250 // ReadSlice returns err != nil if and only if line does not end in delim.
251 func (b *Reader) ReadSlice(delim byte) (line []byte, err os.Error) {
253 if i := bytes.IndexByte(b.buf[b.r:b.w], delim); i >= 0 {
254 line1 := b.buf[b.r : b.r+i+1]
259 // Read more into buffer, until buffer fills or we find delim.
262 line := b.buf[b.r:b.w]
270 // Search new part of buffer
271 if i := bytes.IndexByte(b.buf[n:b.w], delim); i >= 0 {
272 line := b.buf[0 : n+i+1]
278 if b.Buffered() >= len(b.buf) {
280 return b.buf, ErrBufferFull
286 // ReadBytes reads until the first occurrence of delim in the input,
287 // returning a slice containing the data up to and including the delimiter.
288 // If ReadBytes encounters an error before finding a delimiter,
289 // it returns the data read before the error and the error itself (often os.EOF).
290 // ReadBytes returns err != nil if and only if line does not end in delim.
291 func (b *Reader) ReadBytes(delim byte) (line []byte, err os.Error) {
292 // Use ReadSlice to look for array,
293 // accumulating full buffers.
300 frag, e = b.ReadSlice(delim)
301 if e == nil { // got final fragment
304 if e != ErrBufferFull { // unexpected error
309 // Make a copy of the buffer.
310 buf := make([]byte, len(frag))
312 full = append(full, buf)
315 // Allocate new buffer to hold the full pieces and the fragment.
317 for i := range full {
322 // Copy full pieces and fragment in.
323 buf := make([]byte, n)
325 for i := range full {
326 n += copy(buf[n:], full[i])
332 // ReadString reads until the first occurrence of delim in the input,
333 // returning a string containing the data up to and including the delimiter.
334 // If ReadString encounters an error before finding a delimiter,
335 // it returns the data read before the error and the error itself (often os.EOF).
336 // ReadString returns err != nil if and only if line does not end in delim.
337 func (b *Reader) ReadString(delim byte) (line string, err os.Error) {
338 bytes, e := b.ReadBytes(delim)
339 return string(bytes), e
345 // Writer implements buffering for an io.Writer object.
353 // NewWriterSize creates a new Writer whose buffer has the specified size,
354 // which must be greater than zero. If the argument io.Writer is already a
355 // Writer with large enough size, it returns the underlying Writer.
356 // It returns the Writer and any error.
357 func NewWriterSize(wr io.Writer, size int) (*Writer, os.Error) {
359 return nil, BufSizeError(size)
361 // Is it already a Writer?
362 b, ok := wr.(*Writer)
363 if ok && len(b.buf) >= size {
367 b.buf = make([]byte, size)
372 // NewWriter returns a new Writer whose buffer has the default size.
373 func NewWriter(wr io.Writer) *Writer {
374 b, err := NewWriterSize(wr, defaultBufSize)
376 // cannot happen - defaultBufSize is valid size
382 // Flush writes any buffered data to the underlying io.Writer.
383 func (b *Writer) Flush() os.Error {
387 n, e := b.wr.Write(b.buf[0:b.n])
388 if n < b.n && e == nil {
392 if n > 0 && n < b.n {
393 copy(b.buf[0:b.n-n], b.buf[n:b.n])
403 // Available returns how many bytes are unused in the buffer.
404 func (b *Writer) Available() int { return len(b.buf) - b.n }
406 // Buffered returns the number of bytes that have been written into the current buffer.
407 func (b *Writer) Buffered() int { return b.n }
409 // Write writes the contents of p into the buffer.
410 // It returns the number of bytes written.
411 // If nn < len(p), it also returns an error explaining
412 // why the write is short.
413 func (b *Writer) Write(p []byte) (nn int, err os.Error) {
421 if b.Flush(); b.err != nil {
426 if b.Buffered() == 0 && len(p) >= len(b.buf) {
427 // Large write, empty buffer.
428 // Write directly from p to avoid copy.
429 n, b.err = b.wr.Write(p)
440 copy(b.buf[b.n:b.n+n], p[0:n])
448 // WriteByte writes a single byte.
449 func (b *Writer) WriteByte(c byte) os.Error {
453 if b.Available() <= 0 && b.Flush() != nil {
461 // WriteRune writes a single Unicode code point, returning
462 // the number of bytes written and any error.
463 func (b *Writer) WriteRune(rune int) (size int, err os.Error) {
464 if rune < utf8.RuneSelf {
465 err = b.WriteByte(byte(rune))
476 if b.Flush(); b.err != nil {
481 // Can only happen if buffer is silly small.
482 return b.WriteString(string(rune))
485 size = utf8.EncodeRune(rune, b.buf[b.n:])
490 // WriteString writes a string.
491 // It returns the number of bytes written.
492 // If the count is less than len(s), it also returns an error explaining
493 // why the write is short.
494 func (b *Writer) WriteString(s string) (int, os.Error) {
498 // Common case, worth making fast.
499 if b.Available() >= len(s) || len(b.buf) >= len(s) && b.Flush() == nil {
500 for i := 0; i < len(s); i++ { // loop over bytes, not runes.
506 for i := 0; i < len(s); i++ { // loop over bytes, not runes.
515 // buffered input and output
517 // ReadWriter stores pointers to a Reader and a Writer.
518 // It implements io.ReadWriter.
519 type ReadWriter struct {
524 // NewReadWriter allocates a new ReadWriter that dispatches to r and w.
525 func NewReadWriter(r *Reader, w *Writer) *ReadWriter {
526 return &ReadWriter{r, w}