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.
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 return nil, ErrBufferFull
130 // 0 <= n <= len(b.buf)
131 for b
.w
-b
.r
< n
&& b
.err
== nil {
132 b
.fill() // b.w-b.r < len(b.buf) => buffer is not full
145 return b
.buf
[b
.r
: b
.r
+m
], err
148 // Read reads data into p.
149 // It returns the number of bytes read into p.
150 // It calls Read at most once on the underlying Reader,
151 // hence n may be less than len(p).
152 // At EOF, the count will be zero and err will be io.EOF.
153 func (b
*Reader
) Read(p
[]byte) (n
int, err error
) {
156 return 0, b
.readErr()
160 return 0, b
.readErr()
162 if len(p
) >= len(b
.buf
) {
163 // Large read, empty buffer.
164 // Read directly into p to avoid copy.
165 n
, b
.err
= b
.rd
.Read(p
)
167 panic(errNegativeRead
)
170 b
.lastByte
= int(p
[n
-1])
173 return n
, b
.readErr()
175 b
.fill() // buffer is empty
177 return 0, b
.readErr()
184 copy(p
[0:n
], b
.buf
[b
.r
:])
186 b
.lastByte
= int(b
.buf
[b
.r
-1])
191 // ReadByte reads and returns a single byte.
192 // If no byte is available, returns an error.
193 func (b
*Reader
) ReadByte() (c
byte, err error
) {
197 return 0, b
.readErr()
199 b
.fill() // buffer is empty
207 // UnreadByte unreads the last byte. Only the most recently read byte can be unread.
208 func (b
*Reader
) UnreadByte() error
{
209 if b
.lastByte
< 0 || b
.r
== 0 && b
.w
> 0 {
210 return ErrInvalidUnreadByte
212 // b.r > 0 || b.w == 0
216 // b.r == 0 && b.w == 0
219 b
.buf
[b
.r
] = byte(b
.lastByte
)
225 // ReadRune reads a single UTF-8 encoded Unicode character and returns the
226 // rune and its size in bytes. If the encoded rune is invalid, it consumes one byte
227 // and returns unicode.ReplacementChar (U+FFFD) with a size of 1.
228 func (b
*Reader
) ReadRune() (r rune
, size
int, err error
) {
229 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
) {
230 b
.fill() // b.w-b.r < len(buf) => buffer is not full
234 return 0, 0, b
.readErr()
236 r
, size
= rune(b
.buf
[b
.r
]), 1
238 r
, size
= utf8
.DecodeRune(b
.buf
[b
.r
:b
.w
])
241 b
.lastByte
= int(b
.buf
[b
.r
-1])
242 b
.lastRuneSize
= size
246 // UnreadRune unreads the last rune. If the most recent read operation on
247 // the buffer was not a ReadRune, UnreadRune returns an error. (In this
248 // regard it is stricter than UnreadByte, which will unread the last byte
249 // from any read operation.)
250 func (b
*Reader
) UnreadRune() error
{
251 if b
.lastRuneSize
< 0 || b
.r
< b
.lastRuneSize
{
252 return ErrInvalidUnreadRune
254 b
.r
-= b
.lastRuneSize
260 // Buffered returns the number of bytes that can be read from the current buffer.
261 func (b
*Reader
) Buffered() int { return b
.w
- b
.r
}
263 // ReadSlice reads until the first occurrence of delim in the input,
264 // returning a slice pointing at the bytes in the buffer.
265 // The bytes stop being valid at the next read.
266 // If ReadSlice encounters an error before finding a delimiter,
267 // it returns all the data in the buffer and the error itself (often io.EOF).
268 // ReadSlice fails with error ErrBufferFull if the buffer fills without a delim.
269 // Because the data returned from ReadSlice will be overwritten
270 // by the next I/O operation, most clients should use
271 // ReadBytes or ReadString instead.
272 // ReadSlice returns err != nil if and only if line does not end in delim.
273 func (b
*Reader
) ReadSlice(delim
byte) (line
[]byte, err error
) {
276 if i
:= bytes
.IndexByte(b
.buf
[b
.r
:b
.w
], delim
); i
>= 0 {
277 line
= b
.buf
[b
.r
: b
.r
+i
+1]
284 line
= b
.buf
[b
.r
:b
.w
]
291 if n
:= b
.Buffered(); n
>= len(b
.buf
) {
298 b
.fill() // buffer is not full
301 // Handle last byte, if any.
302 if i
:= len(line
) - 1; i
>= 0 {
303 b
.lastByte
= int(line
[i
])
309 // ReadLine is a low-level line-reading primitive. Most callers should use
310 // ReadBytes('\n') or ReadString('\n') instead or use a Scanner.
312 // ReadLine tries to return a single line, not including the end-of-line bytes.
313 // If the line was too long for the buffer then isPrefix is set and the
314 // beginning of the line is returned. The rest of the line will be returned
315 // from future calls. isPrefix will be false when returning the last fragment
316 // of the line. The returned buffer is only valid until the next call to
317 // ReadLine. ReadLine either returns a non-nil line or it returns an error,
320 // The text returned from ReadLine does not include the line end ("\r\n" or "\n").
321 // No indication or error is given if the input ends without a final line end.
322 // Calling UnreadByte after ReadLine will always unread the last byte read
323 // (possibly a character belonging to the line end) even if that byte is not
324 // part of the line returned by ReadLine.
325 func (b
*Reader
) ReadLine() (line
[]byte, isPrefix
bool, err error
) {
326 line
, err
= b
.ReadSlice('\n')
327 if err
== ErrBufferFull
{
328 // Handle the case where "\r\n" straddles the buffer.
329 if len(line
) > 0 && line
[len(line
)-1] == '\r' {
330 // Put the '\r' back on buf and drop it from line.
331 // Let the next call to ReadLine check for "\r\n".
333 // should be unreachable
334 panic("bufio: tried to rewind past start of buffer")
337 line
= line
[:len(line
)-1]
339 return line
, true, nil
350 if line
[len(line
)-1] == '\n' {
352 if len(line
) > 1 && line
[len(line
)-2] == '\r' {
355 line
= line
[:len(line
)-drop
]
360 // ReadBytes reads until the first occurrence of delim in the input,
361 // returning a slice containing the data up to and including the delimiter.
362 // If ReadBytes encounters an error before finding a delimiter,
363 // it returns the data read before the error and the error itself (often io.EOF).
364 // ReadBytes returns err != nil if and only if the returned data does not end in
366 // For simple uses, a Scanner may be more convenient.
367 func (b
*Reader
) ReadBytes(delim
byte) (line
[]byte, err error
) {
368 // Use ReadSlice to look for array,
369 // accumulating full buffers.
376 frag
, e
= b
.ReadSlice(delim
)
377 if e
== nil { // got final fragment
380 if e
!= ErrBufferFull
{ // unexpected error
385 // Make a copy of the buffer.
386 buf
:= make([]byte, len(frag
))
388 full
= append(full
, buf
)
391 // Allocate new buffer to hold the full pieces and the fragment.
393 for i
:= range full
{
398 // Copy full pieces and fragment in.
399 buf
:= make([]byte, n
)
401 for i
:= range full
{
402 n
+= copy(buf
[n
:], full
[i
])
408 // ReadString reads until the first occurrence of delim in the input,
409 // returning a string containing the data up to and including the delimiter.
410 // If ReadString encounters an error before finding a delimiter,
411 // it returns the data read before the error and the error itself (often io.EOF).
412 // ReadString returns err != nil if and only if the returned data does not end in
414 // For simple uses, a Scanner may be more convenient.
415 func (b
*Reader
) ReadString(delim
byte) (line
string, err error
) {
416 bytes
, err
:= b
.ReadBytes(delim
)
421 // WriteTo implements io.WriterTo.
422 func (b
*Reader
) WriteTo(w io
.Writer
) (n
int64, err error
) {
423 n
, err
= b
.writeBuf(w
)
428 if r
, ok
:= b
.rd
.(io
.WriterTo
); ok
{
429 m
, err
:= r
.WriteTo(w
)
434 if w
, ok
:= w
.(io
.ReaderFrom
); ok
{
435 m
, err
:= w
.ReadFrom(b
.rd
)
440 if b
.w
-b
.r
< len(b
.buf
) {
441 b
.fill() // buffer not full
445 // b.r < b.w => buffer is not empty
446 m
, err
:= b
.writeBuf(w
)
451 b
.fill() // buffer is empty
458 return n
, b
.readErr()
461 // writeBuf writes the Reader's buffer to the writer.
462 func (b
*Reader
) writeBuf(w io
.Writer
) (int64, error
) {
463 n
, err
:= w
.Write(b
.buf
[b
.r
:b
.w
])
465 panic(errors
.New("bufio: writer did not write all data"))
473 // Writer implements buffering for an io.Writer object.
474 // If an error occurs writing to a Writer, no more data will be
475 // accepted and all subsequent writes will return the error.
476 // After all data has been written, the client should call the
477 // Flush method to guarantee all data has been forwarded to
478 // the underlying io.Writer.
486 // NewWriterSize returns a new Writer whose buffer has at least the specified
487 // size. If the argument io.Writer is already a Writer with large enough
488 // size, it returns the underlying Writer.
489 func NewWriterSize(w io
.Writer
, size
int) *Writer
{
490 // Is it already a Writer?
492 if ok
&& len(b
.buf
) >= size
{
496 size
= defaultBufSize
499 buf
: make([]byte, size
),
504 // NewWriter returns a new Writer whose buffer has the default size.
505 func NewWriter(w io
.Writer
) *Writer
{
506 return NewWriterSize(w
, defaultBufSize
)
509 // Reset discards any unflushed buffered data, clears any error, and
510 // resets b to write its output to w.
511 func (b
*Writer
) Reset(w io
.Writer
) {
517 // Flush writes any buffered data to the underlying io.Writer.
518 func (b
*Writer
) Flush() error
{
523 func (b
*Writer
) flush() error
{
530 n
, err
:= b
.wr
.Write(b
.buf
[0:b
.n
])
531 if n
< b
.n
&& err
== nil {
532 err
= io
.ErrShortWrite
535 if n
> 0 && n
< b
.n
{
536 copy(b
.buf
[0:b
.n
-n
], b
.buf
[n
:b
.n
])
546 // Available returns how many bytes are unused in the buffer.
547 func (b
*Writer
) Available() int { return len(b
.buf
) - b
.n
}
549 // Buffered returns the number of bytes that have been written into the current buffer.
550 func (b
*Writer
) Buffered() int { return b
.n
}
552 // Write writes the contents of p into the buffer.
553 // It returns the number of bytes written.
554 // If nn < len(p), it also returns an error explaining
555 // why the write is short.
556 func (b
*Writer
) Write(p
[]byte) (nn
int, err error
) {
557 for len(p
) > b
.Available() && b
.err
== nil {
559 if b
.Buffered() == 0 {
560 // Large write, empty buffer.
561 // Write directly from p to avoid copy.
562 n
, b
.err
= b
.wr
.Write(p
)
564 n
= copy(b
.buf
[b
.n
:], p
)
574 n
:= copy(b
.buf
[b
.n
:], p
)
580 // WriteByte writes a single byte.
581 func (b
*Writer
) WriteByte(c
byte) error
{
585 if b
.Available() <= 0 && b
.flush() != nil {
593 // WriteRune writes a single Unicode code point, returning
594 // the number of bytes written and any error.
595 func (b
*Writer
) WriteRune(r rune
) (size
int, err error
) {
596 if r
< utf8
.RuneSelf
{
597 err
= b
.WriteByte(byte(r
))
608 if b
.flush(); b
.err
!= nil {
613 // Can only happen if buffer is silly small.
614 return b
.WriteString(string(r
))
617 size
= utf8
.EncodeRune(b
.buf
[b
.n
:], r
)
622 // WriteString writes a string.
623 // It returns the number of bytes written.
624 // If the count is less than len(s), it also returns an error explaining
625 // why the write is short.
626 func (b
*Writer
) WriteString(s
string) (int, error
) {
628 for len(s
) > b
.Available() && b
.err
== nil {
629 n
:= copy(b
.buf
[b
.n
:], s
)
638 n
:= copy(b
.buf
[b
.n
:], s
)
644 // ReadFrom implements io.ReaderFrom.
645 func (b
*Writer
) ReadFrom(r io
.Reader
) (n
int64, err error
) {
646 if b
.Buffered() == 0 {
647 if w
, ok
:= b
.wr
.(io
.ReaderFrom
); ok
{
653 if b
.Available() == 0 {
654 if err1
:= b
.flush(); err1
!= nil {
659 for nr
< maxConsecutiveEmptyReads
{
660 m
, err
= r
.Read(b
.buf
[b
.n
:])
661 if m
!= 0 || err
!= nil {
666 if nr
== maxConsecutiveEmptyReads
{
667 return n
, io
.ErrNoProgress
676 // If we filled the buffer exactly, flush pre-emptively.
677 if b
.Available() == 0 {
686 // buffered input and output
688 // ReadWriter stores pointers to a Reader and a Writer.
689 // It implements io.ReadWriter.
690 type ReadWriter
struct {
695 // NewReadWriter allocates a new ReadWriter that dispatches to r and w.
696 func NewReadWriter(r
*Reader
, w
*Writer
) *ReadWriter
{
697 return &ReadWriter
{r
, w
}