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 // Package bufio 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.
22 ErrInvalidUnreadByte
= errors
.New("bufio: invalid use of UnreadByte")
23 ErrInvalidUnreadRune
= errors
.New("bufio: invalid use of UnreadRune")
24 ErrBufferFull
= errors
.New("bufio: buffer full")
25 ErrNegativeCount
= errors
.New("bufio: negative count")
30 // Reader implements buffering for an io.Reader object.
33 rd io
.Reader
// reader provided by the client
34 r
, w
int // buf read and write positions
40 const minReadBufferSize
= 16
41 const maxConsecutiveEmptyReads
= 100
43 // NewReaderSize returns a new Reader whose buffer has at least the specified
44 // size. If the argument io.Reader is already a Reader with large enough
45 // size, it returns the underlying Reader.
46 func NewReaderSize(rd io
.Reader
, size
int) *Reader
{
47 // Is it already a Reader?
49 if ok
&& len(b
.buf
) >= size
{
52 if size
< minReadBufferSize
{
53 size
= minReadBufferSize
56 r
.reset(make([]byte, size
), rd
)
60 // NewReader returns a new Reader whose buffer has the default size.
61 func NewReader(rd io
.Reader
) *Reader
{
62 return NewReaderSize(rd
, defaultBufSize
)
65 // Reset discards any buffered data, resets all state, and switches
66 // the buffered reader to read from r.
67 func (b
*Reader
) Reset(r io
.Reader
) {
71 func (b
*Reader
) reset(buf
[]byte, r io
.Reader
) {
80 var errNegativeRead
= errors
.New("bufio: reader returned negative count from Read")
82 // fill reads a new chunk into the buffer.
83 func (b
*Reader
) fill() {
84 // Slide existing data to beginning.
86 copy(b
.buf
, b
.buf
[b
.r
:b
.w
])
91 if b
.w
>= len(b
.buf
) {
92 panic("bufio: tried to fill full buffer")
95 // Read new data: try a limited number of times.
96 for i
:= maxConsecutiveEmptyReads
; i
> 0; i
-- {
97 n
, err
:= b
.rd
.Read(b
.buf
[b
.w
:])
99 panic(errNegativeRead
)
110 b
.err
= io
.ErrNoProgress
113 func (b
*Reader
) readErr() error
{
119 // Peek returns the next n bytes without advancing the reader. The bytes stop
120 // being valid at the next read call. If Peek returns fewer than n bytes, it
121 // also returns an error explaining why the read is short. The error is
122 // ErrBufferFull if n is larger than b's buffer size.
123 func (b
*Reader
) Peek(n
int) ([]byte, error
) {
125 return nil, ErrNegativeCount
128 for b
.w
-b
.r
< n
&& b
.w
-b
.r
< len(b
.buf
) && b
.err
== nil {
129 b
.fill() // b.w-b.r < len(b.buf) => buffer is not full
133 return b
.buf
[b
.r
:b
.w
], ErrBufferFull
136 // 0 <= n <= len(b.buf)
138 if avail
:= b
.w
- b
.r
; avail
< n
{
139 // not enough data in buffer
146 return b
.buf
[b
.r
: b
.r
+n
], err
149 // Discard skips the next n bytes, returning the number of bytes discarded.
151 // If Discard skips fewer than n bytes, it also returns an error.
152 // If 0 <= n <= b.Buffered(), Discard is guaranteed to succeed without
153 // reading from the underlying io.Reader.
154 func (b
*Reader
) Discard(n
int) (discarded
int, err error
) {
156 return 0, ErrNegativeCount
177 return n
- remain
, b
.readErr()
182 // Read reads data into p.
183 // It returns the number of bytes read into p.
184 // The bytes are taken from at most one Read on the underlying Reader,
185 // hence n may be less than len(p).
186 // At EOF, the count will be zero and err will be io.EOF.
187 func (b
*Reader
) Read(p
[]byte) (n
int, err error
) {
190 return 0, b
.readErr()
194 return 0, b
.readErr()
196 if len(p
) >= len(b
.buf
) {
197 // Large read, empty buffer.
198 // Read directly into p to avoid copy.
199 n
, b
.err
= b
.rd
.Read(p
)
201 panic(errNegativeRead
)
204 b
.lastByte
= int(p
[n
-1])
207 return n
, b
.readErr()
210 // Do not use b.fill, which will loop.
213 n
, b
.err
= b
.rd
.Read(b
.buf
)
215 panic(errNegativeRead
)
218 return 0, b
.readErr()
223 // copy as much as we can
224 n
= copy(p
, b
.buf
[b
.r
:b
.w
])
226 b
.lastByte
= int(b
.buf
[b
.r
-1])
231 // ReadByte reads and returns a single byte.
232 // If no byte is available, returns an error.
233 func (b
*Reader
) ReadByte() (byte, error
) {
237 return 0, b
.readErr()
239 b
.fill() // buffer is empty
247 // UnreadByte unreads the last byte. Only the most recently read byte can be unread.
248 func (b
*Reader
) UnreadByte() error
{
249 if b
.lastByte
< 0 || b
.r
== 0 && b
.w
> 0 {
250 return ErrInvalidUnreadByte
252 // b.r > 0 || b.w == 0
256 // b.r == 0 && b.w == 0
259 b
.buf
[b
.r
] = byte(b
.lastByte
)
265 // ReadRune reads a single UTF-8 encoded Unicode character and returns the
266 // rune and its size in bytes. If the encoded rune is invalid, it consumes one byte
267 // and returns unicode.ReplacementChar (U+FFFD) with a size of 1.
268 func (b
*Reader
) ReadRune() (r rune
, size
int, err error
) {
269 for b
.r
+utf8
.UTFMax
> b
.w
&& !utf8
.FullRune(b
.buf
[b
.r
:b
.w
]) && b
.err
== nil && b
.w
-b
.r
< len(b
.buf
) {
270 b
.fill() // b.w-b.r < len(buf) => buffer is not full
274 return 0, 0, b
.readErr()
276 r
, size
= rune(b
.buf
[b
.r
]), 1
277 if r
>= utf8
.RuneSelf
{
278 r
, size
= utf8
.DecodeRune(b
.buf
[b
.r
:b
.w
])
281 b
.lastByte
= int(b
.buf
[b
.r
-1])
282 b
.lastRuneSize
= size
286 // UnreadRune unreads the last rune. If the most recent read operation on
287 // the buffer was not a ReadRune, UnreadRune returns an error. (In this
288 // regard it is stricter than UnreadByte, which will unread the last byte
289 // from any read operation.)
290 func (b
*Reader
) UnreadRune() error
{
291 if b
.lastRuneSize
< 0 || b
.r
< b
.lastRuneSize
{
292 return ErrInvalidUnreadRune
294 b
.r
-= b
.lastRuneSize
300 // Buffered returns the number of bytes that can be read from the current buffer.
301 func (b
*Reader
) Buffered() int { return b
.w
- b
.r
}
303 // ReadSlice reads until the first occurrence of delim in the input,
304 // returning a slice pointing at the bytes in the buffer.
305 // The bytes stop being valid at the next read.
306 // If ReadSlice encounters an error before finding a delimiter,
307 // it returns all the data in the buffer and the error itself (often io.EOF).
308 // ReadSlice fails with error ErrBufferFull if the buffer fills without a delim.
309 // Because the data returned from ReadSlice will be overwritten
310 // by the next I/O operation, most clients should use
311 // ReadBytes or ReadString instead.
312 // ReadSlice returns err != nil if and only if line does not end in delim.
313 func (b
*Reader
) ReadSlice(delim
byte) (line
[]byte, err error
) {
316 if i
:= bytes
.IndexByte(b
.buf
[b
.r
:b
.w
], delim
); i
>= 0 {
317 line
= b
.buf
[b
.r
: b
.r
+i
+1]
324 line
= b
.buf
[b
.r
:b
.w
]
331 if b
.Buffered() >= len(b
.buf
) {
338 b
.fill() // buffer is not full
341 // Handle last byte, if any.
342 if i
:= len(line
) - 1; i
>= 0 {
343 b
.lastByte
= int(line
[i
])
350 // ReadLine is a low-level line-reading primitive. Most callers should use
351 // ReadBytes('\n') or ReadString('\n') instead or use a Scanner.
353 // ReadLine tries to return a single line, not including the end-of-line bytes.
354 // If the line was too long for the buffer then isPrefix is set and the
355 // beginning of the line is returned. The rest of the line will be returned
356 // from future calls. isPrefix will be false when returning the last fragment
357 // of the line. The returned buffer is only valid until the next call to
358 // ReadLine. ReadLine either returns a non-nil line or it returns an error,
361 // The text returned from ReadLine does not include the line end ("\r\n" or "\n").
362 // No indication or error is given if the input ends without a final line end.
363 // Calling UnreadByte after ReadLine will always unread the last byte read
364 // (possibly a character belonging to the line end) even if that byte is not
365 // part of the line returned by ReadLine.
366 func (b
*Reader
) ReadLine() (line
[]byte, isPrefix
bool, err error
) {
367 line
, err
= b
.ReadSlice('\n')
368 if err
== ErrBufferFull
{
369 // Handle the case where "\r\n" straddles the buffer.
370 if len(line
) > 0 && line
[len(line
)-1] == '\r' {
371 // Put the '\r' back on buf and drop it from line.
372 // Let the next call to ReadLine check for "\r\n".
374 // should be unreachable
375 panic("bufio: tried to rewind past start of buffer")
378 line
= line
[:len(line
)-1]
380 return line
, true, nil
391 if line
[len(line
)-1] == '\n' {
393 if len(line
) > 1 && line
[len(line
)-2] == '\r' {
396 line
= line
[:len(line
)-drop
]
401 // ReadBytes reads until the first occurrence of delim in the input,
402 // returning a slice containing the data up to and including the delimiter.
403 // If ReadBytes encounters an error before finding a delimiter,
404 // it returns the data read before the error and the error itself (often io.EOF).
405 // ReadBytes returns err != nil if and only if the returned data does not end in
407 // For simple uses, a Scanner may be more convenient.
408 func (b
*Reader
) ReadBytes(delim
byte) ([]byte, error
) {
409 // Use ReadSlice to look for array,
410 // accumulating full buffers.
416 frag
, e
= b
.ReadSlice(delim
)
417 if e
== nil { // got final fragment
420 if e
!= ErrBufferFull
{ // unexpected error
425 // Make a copy of the buffer.
426 buf
:= make([]byte, len(frag
))
428 full
= append(full
, buf
)
431 // Allocate new buffer to hold the full pieces and the fragment.
433 for i
:= range full
{
438 // Copy full pieces and fragment in.
439 buf
:= make([]byte, n
)
441 for i
:= range full
{
442 n
+= copy(buf
[n
:], full
[i
])
448 // ReadString reads until the first occurrence of delim in the input,
449 // returning a string containing the data up to and including the delimiter.
450 // If ReadString encounters an error before finding a delimiter,
451 // it returns the data read before the error and the error itself (often io.EOF).
452 // ReadString returns err != nil if and only if the returned data does not end in
454 // For simple uses, a Scanner may be more convenient.
455 func (b
*Reader
) ReadString(delim
byte) (string, error
) {
456 bytes
, err
:= b
.ReadBytes(delim
)
457 return string(bytes
), err
460 // WriteTo implements io.WriterTo.
461 func (b
*Reader
) WriteTo(w io
.Writer
) (n
int64, err error
) {
462 n
, err
= b
.writeBuf(w
)
467 if r
, ok
:= b
.rd
.(io
.WriterTo
); ok
{
468 m
, err
:= r
.WriteTo(w
)
473 if w
, ok
:= w
.(io
.ReaderFrom
); ok
{
474 m
, err
:= w
.ReadFrom(b
.rd
)
479 if b
.w
-b
.r
< len(b
.buf
) {
480 b
.fill() // buffer not full
484 // b.r < b.w => buffer is not empty
485 m
, err
:= b
.writeBuf(w
)
490 b
.fill() // buffer is empty
497 return n
, b
.readErr()
500 var errNegativeWrite
= errors
.New("bufio: writer returned negative count from Write")
502 // writeBuf writes the Reader's buffer to the writer.
503 func (b
*Reader
) writeBuf(w io
.Writer
) (int64, error
) {
504 n
, err
:= w
.Write(b
.buf
[b
.r
:b
.w
])
506 panic(errNegativeWrite
)
514 // Writer implements buffering for an io.Writer object.
515 // If an error occurs writing to a Writer, no more data will be
516 // accepted and all subsequent writes will return the error.
517 // After all data has been written, the client should call the
518 // Flush method to guarantee all data has been forwarded to
519 // the underlying io.Writer.
527 // NewWriterSize returns a new Writer whose buffer has at least the specified
528 // size. If the argument io.Writer is already a Writer with large enough
529 // size, it returns the underlying Writer.
530 func NewWriterSize(w io
.Writer
, size
int) *Writer
{
531 // Is it already a Writer?
533 if ok
&& len(b
.buf
) >= size
{
537 size
= defaultBufSize
540 buf
: make([]byte, size
),
545 // NewWriter returns a new Writer whose buffer has the default size.
546 func NewWriter(w io
.Writer
) *Writer
{
547 return NewWriterSize(w
, defaultBufSize
)
550 // Reset discards any unflushed buffered data, clears any error, and
551 // resets b to write its output to w.
552 func (b
*Writer
) Reset(w io
.Writer
) {
558 // Flush writes any buffered data to the underlying io.Writer.
559 func (b
*Writer
) Flush() error
{
566 n
, err
:= b
.wr
.Write(b
.buf
[0:b
.n
])
567 if n
< b
.n
&& err
== nil {
568 err
= io
.ErrShortWrite
571 if n
> 0 && n
< b
.n
{
572 copy(b
.buf
[0:b
.n
-n
], b
.buf
[n
:b
.n
])
582 // Available returns how many bytes are unused in the buffer.
583 func (b
*Writer
) Available() int { return len(b
.buf
) - b
.n
}
585 // Buffered returns the number of bytes that have been written into the current buffer.
586 func (b
*Writer
) Buffered() int { return b
.n
}
588 // Write writes the contents of p into the buffer.
589 // It returns the number of bytes written.
590 // If nn < len(p), it also returns an error explaining
591 // why the write is short.
592 func (b
*Writer
) Write(p
[]byte) (nn
int, err error
) {
593 for len(p
) > b
.Available() && b
.err
== nil {
595 if b
.Buffered() == 0 {
596 // Large write, empty buffer.
597 // Write directly from p to avoid copy.
598 n
, b
.err
= b
.wr
.Write(p
)
600 n
= copy(b
.buf
[b
.n
:], p
)
610 n
:= copy(b
.buf
[b
.n
:], p
)
616 // WriteByte writes a single byte.
617 func (b
*Writer
) WriteByte(c
byte) error
{
621 if b
.Available() <= 0 && b
.Flush() != nil {
629 // WriteRune writes a single Unicode code point, returning
630 // the number of bytes written and any error.
631 func (b
*Writer
) WriteRune(r rune
) (size
int, err error
) {
632 if r
< utf8
.RuneSelf
{
633 err
= b
.WriteByte(byte(r
))
644 if b
.Flush(); b
.err
!= nil {
649 // Can only happen if buffer is silly small.
650 return b
.WriteString(string(r
))
653 size
= utf8
.EncodeRune(b
.buf
[b
.n
:], r
)
658 // WriteString writes a string.
659 // It returns the number of bytes written.
660 // If the count is less than len(s), it also returns an error explaining
661 // why the write is short.
662 func (b
*Writer
) WriteString(s
string) (int, error
) {
664 for len(s
) > b
.Available() && b
.err
== nil {
665 n
:= copy(b
.buf
[b
.n
:], s
)
674 n
:= copy(b
.buf
[b
.n
:], s
)
680 // ReadFrom implements io.ReaderFrom.
681 func (b
*Writer
) ReadFrom(r io
.Reader
) (n
int64, err error
) {
682 if b
.Buffered() == 0 {
683 if w
, ok
:= b
.wr
.(io
.ReaderFrom
); ok
{
689 if b
.Available() == 0 {
690 if err1
:= b
.Flush(); err1
!= nil {
695 for nr
< maxConsecutiveEmptyReads
{
696 m
, err
= r
.Read(b
.buf
[b
.n
:])
697 if m
!= 0 || err
!= nil {
702 if nr
== maxConsecutiveEmptyReads
{
703 return n
, io
.ErrNoProgress
712 // If we filled the buffer exactly, flush preemptively.
713 if b
.Available() == 0 {
722 // buffered input and output
724 // ReadWriter stores pointers to a Reader and a Writer.
725 // It implements io.ReadWriter.
726 type ReadWriter
struct {
731 // NewReadWriter allocates a new ReadWriter that dispatches to r and w.
732 func NewReadWriter(r
*Reader
, w
*Writer
) *ReadWriter
{
733 return &ReadWriter
{r
, w
}