Source file src/bufio/bufio.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 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.
     8  package bufio
     9  
    10  import (
    11  	"bytes"
    12  	"errors"
    13  	"io"
    14  	"strings"
    15  	"unicode/utf8"
    16  )
    17  
    18  const (
    19  	defaultBufSize = 4096
    20  )
    21  
    22  var (
    23  	ErrInvalidUnreadByte = errors.New("bufio: invalid use of UnreadByte")
    24  	ErrInvalidUnreadRune = errors.New("bufio: invalid use of UnreadRune")
    25  	ErrBufferFull        = errors.New("bufio: buffer full")
    26  	ErrNegativeCount     = errors.New("bufio: negative count")
    27  )
    28  
    29  // Buffered input.
    30  
    31  // Reader implements buffering for an io.Reader object.
    32  type Reader struct {
    33  	buf          []byte
    34  	rd           io.Reader // reader provided by the client
    35  	r, w         int       // buf read and write positions
    36  	err          error
    37  	lastByte     int // last byte read for UnreadByte; -1 means invalid
    38  	lastRuneSize int // size of last rune read for UnreadRune; -1 means invalid
    39  }
    40  
    41  const minReadBufferSize = 16
    42  const maxConsecutiveEmptyReads = 100
    43  
    44  // NewReaderSize returns a new Reader whose buffer has at least the specified
    45  // size. If the argument io.Reader is already a Reader with large enough
    46  // size, it returns the underlying Reader.
    47  func NewReaderSize(rd io.Reader, size int) *Reader {
    48  	// Is it already a Reader?
    49  	b, ok := rd.(*Reader)
    50  	if ok && len(b.buf) >= size {
    51  		return b
    52  	}
    53  	if size < minReadBufferSize {
    54  		size = minReadBufferSize
    55  	}
    56  	r := new(Reader)
    57  	r.reset(make([]byte, size), rd)
    58  	return r
    59  }
    60  
    61  // NewReader returns a new Reader whose buffer has the default size.
    62  func NewReader(rd io.Reader) *Reader {
    63  	return NewReaderSize(rd, defaultBufSize)
    64  }
    65  
    66  // Size returns the size of the underlying buffer in bytes.
    67  func (b *Reader) Size() int { return len(b.buf) }
    68  
    69  // Reset discards any buffered data, resets all state, and switches
    70  // the buffered reader to read from r.
    71  // Calling Reset on the zero value of Reader initializes the internal buffer
    72  // to the default size.
    73  func (b *Reader) Reset(r io.Reader) {
    74  	if b.buf == nil {
    75  		b.buf = make([]byte, defaultBufSize)
    76  	}
    77  	b.reset(b.buf, r)
    78  }
    79  
    80  func (b *Reader) reset(buf []byte, r io.Reader) {
    81  	*b = Reader{
    82  		buf:          buf,
    83  		rd:           r,
    84  		lastByte:     -1,
    85  		lastRuneSize: -1,
    86  	}
    87  }
    88  
    89  var errNegativeRead = errors.New("bufio: reader returned negative count from Read")
    90  
    91  // fill reads a new chunk into the buffer.
    92  func (b *Reader) fill() {
    93  	// Slide existing data to beginning.
    94  	if b.r > 0 {
    95  		copy(b.buf, b.buf[b.r:b.w])
    96  		b.w -= b.r
    97  		b.r = 0
    98  	}
    99  
   100  	if b.w >= len(b.buf) {
   101  		panic("bufio: tried to fill full buffer")
   102  	}
   103  
   104  	// Read new data: try a limited number of times.
   105  	for i := maxConsecutiveEmptyReads; i > 0; i-- {
   106  		n, err := b.rd.Read(b.buf[b.w:])
   107  		if n < 0 {
   108  			panic(errNegativeRead)
   109  		}
   110  		b.w += n
   111  		if err != nil {
   112  			b.err = err
   113  			return
   114  		}
   115  		if n > 0 {
   116  			return
   117  		}
   118  	}
   119  	b.err = io.ErrNoProgress
   120  }
   121  
   122  func (b *Reader) readErr() error {
   123  	err := b.err
   124  	b.err = nil
   125  	return err
   126  }
   127  
   128  // Peek returns the next n bytes without advancing the reader. The bytes stop
   129  // being valid at the next read call. If Peek returns fewer than n bytes, it
   130  // also returns an error explaining why the read is short. The error is
   131  // ErrBufferFull if n is larger than b's buffer size.
   132  //
   133  // Calling Peek prevents a UnreadByte or UnreadRune call from succeeding
   134  // until the next read operation.
   135  func (b *Reader) Peek(n int) ([]byte, error) {
   136  	if n < 0 {
   137  		return nil, ErrNegativeCount
   138  	}
   139  
   140  	b.lastByte = -1
   141  	b.lastRuneSize = -1
   142  
   143  	for b.w-b.r < n && b.w-b.r < len(b.buf) && b.err == nil {
   144  		b.fill() // b.w-b.r < len(b.buf) => buffer is not full
   145  	}
   146  
   147  	if n > len(b.buf) {
   148  		return b.buf[b.r:b.w], ErrBufferFull
   149  	}
   150  
   151  	// 0 <= n <= len(b.buf)
   152  	var err error
   153  	if avail := b.w - b.r; avail < n {
   154  		// not enough data in buffer
   155  		n = avail
   156  		err = b.readErr()
   157  		if err == nil {
   158  			err = ErrBufferFull
   159  		}
   160  	}
   161  	return b.buf[b.r : b.r+n], err
   162  }
   163  
   164  // Discard skips the next n bytes, returning the number of bytes discarded.
   165  //
   166  // If Discard skips fewer than n bytes, it also returns an error.
   167  // If 0 <= n <= b.Buffered(), Discard is guaranteed to succeed without
   168  // reading from the underlying io.Reader.
   169  func (b *Reader) Discard(n int) (discarded int, err error) {
   170  	if n < 0 {
   171  		return 0, ErrNegativeCount
   172  	}
   173  	if n == 0 {
   174  		return
   175  	}
   176  
   177  	b.lastByte = -1
   178  	b.lastRuneSize = -1
   179  
   180  	remain := n
   181  	for {
   182  		skip := b.Buffered()
   183  		if skip == 0 {
   184  			b.fill()
   185  			skip = b.Buffered()
   186  		}
   187  		if skip > remain {
   188  			skip = remain
   189  		}
   190  		b.r += skip
   191  		remain -= skip
   192  		if remain == 0 {
   193  			return n, nil
   194  		}
   195  		if b.err != nil {
   196  			return n - remain, b.readErr()
   197  		}
   198  	}
   199  }
   200  
   201  // Read reads data into p.
   202  // It returns the number of bytes read into p.
   203  // The bytes are taken from at most one Read on the underlying Reader,
   204  // hence n may be less than len(p).
   205  // To read exactly len(p) bytes, use io.ReadFull(b, p).
   206  // At EOF, the count will be zero and err will be io.EOF.
   207  func (b *Reader) Read(p []byte) (n int, err error) {
   208  	n = len(p)
   209  	if n == 0 {
   210  		if b.Buffered() > 0 {
   211  			return 0, nil
   212  		}
   213  		return 0, b.readErr()
   214  	}
   215  	if b.r == b.w {
   216  		if b.err != nil {
   217  			return 0, b.readErr()
   218  		}
   219  		if len(p) >= len(b.buf) {
   220  			// Large read, empty buffer.
   221  			// Read directly into p to avoid copy.
   222  			n, b.err = b.rd.Read(p)
   223  			if n < 0 {
   224  				panic(errNegativeRead)
   225  			}
   226  			if n > 0 {
   227  				b.lastByte = int(p[n-1])
   228  				b.lastRuneSize = -1
   229  			}
   230  			return n, b.readErr()
   231  		}
   232  		// One read.
   233  		// Do not use b.fill, which will loop.
   234  		b.r = 0
   235  		b.w = 0
   236  		n, b.err = b.rd.Read(b.buf)
   237  		if n < 0 {
   238  			panic(errNegativeRead)
   239  		}
   240  		if n == 0 {
   241  			return 0, b.readErr()
   242  		}
   243  		b.w += n
   244  	}
   245  
   246  	// copy as much as we can
   247  	// Note: if the slice panics here, it is probably because
   248  	// the underlying reader returned a bad count. See issue 49795.
   249  	n = copy(p, b.buf[b.r:b.w])
   250  	b.r += n
   251  	b.lastByte = int(b.buf[b.r-1])
   252  	b.lastRuneSize = -1
   253  	return n, nil
   254  }
   255  
   256  // ReadByte reads and returns a single byte.
   257  // If no byte is available, returns an error.
   258  func (b *Reader) ReadByte() (byte, error) {
   259  	b.lastRuneSize = -1
   260  	for b.r == b.w {
   261  		if b.err != nil {
   262  			return 0, b.readErr()
   263  		}
   264  		b.fill() // buffer is empty
   265  	}
   266  	c := b.buf[b.r]
   267  	b.r++
   268  	b.lastByte = int(c)
   269  	return c, nil
   270  }
   271  
   272  // UnreadByte unreads the last byte. Only the most recently read byte can be unread.
   273  //
   274  // UnreadByte returns an error if the most recent method called on the
   275  // Reader was not a read operation. Notably, Peek, Discard, and WriteTo are not
   276  // considered read operations.
   277  func (b *Reader) UnreadByte() error {
   278  	if b.lastByte < 0 || b.r == 0 && b.w > 0 {
   279  		return ErrInvalidUnreadByte
   280  	}
   281  	// b.r > 0 || b.w == 0
   282  	if b.r > 0 {
   283  		b.r--
   284  	} else {
   285  		// b.r == 0 && b.w == 0
   286  		b.w = 1
   287  	}
   288  	b.buf[b.r] = byte(b.lastByte)
   289  	b.lastByte = -1
   290  	b.lastRuneSize = -1
   291  	return nil
   292  }
   293  
   294  // ReadRune reads a single UTF-8 encoded Unicode character and returns the
   295  // rune and its size in bytes. If the encoded rune is invalid, it consumes one byte
   296  // and returns unicode.ReplacementChar (U+FFFD) with a size of 1.
   297  func (b *Reader) ReadRune() (r rune, size int, err error) {
   298  	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) {
   299  		b.fill() // b.w-b.r < len(buf) => buffer is not full
   300  	}
   301  	b.lastRuneSize = -1
   302  	if b.r == b.w {
   303  		return 0, 0, b.readErr()
   304  	}
   305  	r, size = rune(b.buf[b.r]), 1
   306  	if r >= utf8.RuneSelf {
   307  		r, size = utf8.DecodeRune(b.buf[b.r:b.w])
   308  	}
   309  	b.r += size
   310  	b.lastByte = int(b.buf[b.r-1])
   311  	b.lastRuneSize = size
   312  	return r, size, nil
   313  }
   314  
   315  // UnreadRune unreads the last rune. If the most recent method called on
   316  // the Reader was not a ReadRune, UnreadRune returns an error. (In this
   317  // regard it is stricter than UnreadByte, which will unread the last byte
   318  // from any read operation.)
   319  func (b *Reader) UnreadRune() error {
   320  	if b.lastRuneSize < 0 || b.r < b.lastRuneSize {
   321  		return ErrInvalidUnreadRune
   322  	}
   323  	b.r -= b.lastRuneSize
   324  	b.lastByte = -1
   325  	b.lastRuneSize = -1
   326  	return nil
   327  }
   328  
   329  // Buffered returns the number of bytes that can be read from the current buffer.
   330  func (b *Reader) Buffered() int { return b.w - b.r }
   331  
   332  // ReadSlice reads until the first occurrence of delim in the input,
   333  // returning a slice pointing at the bytes in the buffer.
   334  // The bytes stop being valid at the next read.
   335  // If ReadSlice encounters an error before finding a delimiter,
   336  // it returns all the data in the buffer and the error itself (often io.EOF).
   337  // ReadSlice fails with error ErrBufferFull if the buffer fills without a delim.
   338  // Because the data returned from ReadSlice will be overwritten
   339  // by the next I/O operation, most clients should use
   340  // ReadBytes or ReadString instead.
   341  // ReadSlice returns err != nil if and only if line does not end in delim.
   342  func (b *Reader) ReadSlice(delim byte) (line []byte, err error) {
   343  	s := 0 // search start index
   344  	for {
   345  		// Search buffer.
   346  		if i := bytes.IndexByte(b.buf[b.r+s:b.w], delim); i >= 0 {
   347  			i += s
   348  			line = b.buf[b.r : b.r+i+1]
   349  			b.r += i + 1
   350  			break
   351  		}
   352  
   353  		// Pending error?
   354  		if b.err != nil {
   355  			line = b.buf[b.r:b.w]
   356  			b.r = b.w
   357  			err = b.readErr()
   358  			break
   359  		}
   360  
   361  		// Buffer full?
   362  		if b.Buffered() >= len(b.buf) {
   363  			b.r = b.w
   364  			line = b.buf
   365  			err = ErrBufferFull
   366  			break
   367  		}
   368  
   369  		s = b.w - b.r // do not rescan area we scanned before
   370  
   371  		b.fill() // buffer is not full
   372  	}
   373  
   374  	// Handle last byte, if any.
   375  	if i := len(line) - 1; i >= 0 {
   376  		b.lastByte = int(line[i])
   377  		b.lastRuneSize = -1
   378  	}
   379  
   380  	return
   381  }
   382  
   383  // ReadLine is a low-level line-reading primitive. Most callers should use
   384  // ReadBytes('\n') or ReadString('\n') instead or use a Scanner.
   385  //
   386  // ReadLine tries to return a single line, not including the end-of-line bytes.
   387  // If the line was too long for the buffer then isPrefix is set and the
   388  // beginning of the line is returned. The rest of the line will be returned
   389  // from future calls. isPrefix will be false when returning the last fragment
   390  // of the line. The returned buffer is only valid until the next call to
   391  // ReadLine. ReadLine either returns a non-nil line or it returns an error,
   392  // never both.
   393  //
   394  // The text returned from ReadLine does not include the line end ("\r\n" or "\n").
   395  // No indication or error is given if the input ends without a final line end.
   396  // Calling UnreadByte after ReadLine will always unread the last byte read
   397  // (possibly a character belonging to the line end) even if that byte is not
   398  // part of the line returned by ReadLine.
   399  func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error) {
   400  	line, err = b.ReadSlice('\n')
   401  	if err == ErrBufferFull {
   402  		// Handle the case where "\r\n" straddles the buffer.
   403  		if len(line) > 0 && line[len(line)-1] == '\r' {
   404  			// Put the '\r' back on buf and drop it from line.
   405  			// Let the next call to ReadLine check for "\r\n".
   406  			if b.r == 0 {
   407  				// should be unreachable
   408  				panic("bufio: tried to rewind past start of buffer")
   409  			}
   410  			b.r--
   411  			line = line[:len(line)-1]
   412  		}
   413  		return line, true, nil
   414  	}
   415  
   416  	if len(line) == 0 {
   417  		if err != nil {
   418  			line = nil
   419  		}
   420  		return
   421  	}
   422  	err = nil
   423  
   424  	if line[len(line)-1] == '\n' {
   425  		drop := 1
   426  		if len(line) > 1 && line[len(line)-2] == '\r' {
   427  			drop = 2
   428  		}
   429  		line = line[:len(line)-drop]
   430  	}
   431  	return
   432  }
   433  
   434  // collectFragments reads until the first occurrence of delim in the input. It
   435  // returns (slice of full buffers, remaining bytes before delim, total number
   436  // of bytes in the combined first two elements, error).
   437  // The complete result is equal to
   438  // `bytes.Join(append(fullBuffers, finalFragment), nil)`, which has a
   439  // length of `totalLen`. The result is structured in this way to allow callers
   440  // to minimize allocations and copies.
   441  func (b *Reader) collectFragments(delim byte) (fullBuffers [][]byte, finalFragment []byte, totalLen int, err error) {
   442  	var frag []byte
   443  	// Use ReadSlice to look for delim, accumulating full buffers.
   444  	for {
   445  		var e error
   446  		frag, e = b.ReadSlice(delim)
   447  		if e == nil { // got final fragment
   448  			break
   449  		}
   450  		if e != ErrBufferFull { // unexpected error
   451  			err = e
   452  			break
   453  		}
   454  
   455  		// Make a copy of the buffer.
   456  		buf := make([]byte, len(frag))
   457  		copy(buf, frag)
   458  		fullBuffers = append(fullBuffers, buf)
   459  		totalLen += len(buf)
   460  	}
   461  
   462  	totalLen += len(frag)
   463  	return fullBuffers, frag, totalLen, err
   464  }
   465  
   466  // ReadBytes reads until the first occurrence of delim in the input,
   467  // returning a slice containing the data up to and including the delimiter.
   468  // If ReadBytes encounters an error before finding a delimiter,
   469  // it returns the data read before the error and the error itself (often io.EOF).
   470  // ReadBytes returns err != nil if and only if the returned data does not end in
   471  // delim.
   472  // For simple uses, a Scanner may be more convenient.
   473  func (b *Reader) ReadBytes(delim byte) ([]byte, error) {
   474  	full, frag, n, err := b.collectFragments(delim)
   475  	// Allocate new buffer to hold the full pieces and the fragment.
   476  	buf := make([]byte, n)
   477  	n = 0
   478  	// Copy full pieces and fragment in.
   479  	for i := range full {
   480  		n += copy(buf[n:], full[i])
   481  	}
   482  	copy(buf[n:], frag)
   483  	return buf, err
   484  }
   485  
   486  // ReadString reads until the first occurrence of delim in the input,
   487  // returning a string containing the data up to and including the delimiter.
   488  // If ReadString encounters an error before finding a delimiter,
   489  // it returns the data read before the error and the error itself (often io.EOF).
   490  // ReadString returns err != nil if and only if the returned data does not end in
   491  // delim.
   492  // For simple uses, a Scanner may be more convenient.
   493  func (b *Reader) ReadString(delim byte) (string, error) {
   494  	full, frag, n, err := b.collectFragments(delim)
   495  	// Allocate new buffer to hold the full pieces and the fragment.
   496  	var buf strings.Builder
   497  	buf.Grow(n)
   498  	// Copy full pieces and fragment in.
   499  	for _, fb := range full {
   500  		buf.Write(fb)
   501  	}
   502  	buf.Write(frag)
   503  	return buf.String(), err
   504  }
   505  
   506  // WriteTo implements io.WriterTo.
   507  // This may make multiple calls to the Read method of the underlying Reader.
   508  // If the underlying reader supports the WriteTo method,
   509  // this calls the underlying WriteTo without buffering.
   510  func (b *Reader) WriteTo(w io.Writer) (n int64, err error) {
   511  	b.lastByte = -1
   512  	b.lastRuneSize = -1
   513  
   514  	n, err = b.writeBuf(w)
   515  	if err != nil {
   516  		return
   517  	}
   518  
   519  	if r, ok := b.rd.(io.WriterTo); ok {
   520  		m, err := r.WriteTo(w)
   521  		n += m
   522  		return n, err
   523  	}
   524  
   525  	if w, ok := w.(io.ReaderFrom); ok {
   526  		m, err := w.ReadFrom(b.rd)
   527  		n += m
   528  		return n, err
   529  	}
   530  
   531  	if b.w-b.r < len(b.buf) {
   532  		b.fill() // buffer not full
   533  	}
   534  
   535  	for b.r < b.w {
   536  		// b.r < b.w => buffer is not empty
   537  		m, err := b.writeBuf(w)
   538  		n += m
   539  		if err != nil {
   540  			return n, err
   541  		}
   542  		b.fill() // buffer is empty
   543  	}
   544  
   545  	if b.err == io.EOF {
   546  		b.err = nil
   547  	}
   548  
   549  	return n, b.readErr()
   550  }
   551  
   552  var errNegativeWrite = errors.New("bufio: writer returned negative count from Write")
   553  
   554  // writeBuf writes the Reader's buffer to the writer.
   555  func (b *Reader) writeBuf(w io.Writer) (int64, error) {
   556  	n, err := w.Write(b.buf[b.r:b.w])
   557  	if n < 0 {
   558  		panic(errNegativeWrite)
   559  	}
   560  	b.r += n
   561  	return int64(n), err
   562  }
   563  
   564  // buffered output
   565  
   566  // Writer implements buffering for an io.Writer object.
   567  // If an error occurs writing to a Writer, no more data will be
   568  // accepted and all subsequent writes, and Flush, will return the error.
   569  // After all data has been written, the client should call the
   570  // Flush method to guarantee all data has been forwarded to
   571  // the underlying io.Writer.
   572  type Writer struct {
   573  	err error
   574  	buf []byte
   575  	n   int
   576  	wr  io.Writer
   577  }
   578  
   579  // NewWriterSize returns a new Writer whose buffer has at least the specified
   580  // size. If the argument io.Writer is already a Writer with large enough
   581  // size, it returns the underlying Writer.
   582  func NewWriterSize(w io.Writer, size int) *Writer {
   583  	// Is it already a Writer?
   584  	b, ok := w.(*Writer)
   585  	if ok && len(b.buf) >= size {
   586  		return b
   587  	}
   588  	if size <= 0 {
   589  		size = defaultBufSize
   590  	}
   591  	return &Writer{
   592  		buf: make([]byte, size),
   593  		wr:  w,
   594  	}
   595  }
   596  
   597  // NewWriter returns a new Writer whose buffer has the default size.
   598  // If the argument io.Writer is already a Writer with large enough buffer size,
   599  // it returns the underlying Writer.
   600  func NewWriter(w io.Writer) *Writer {
   601  	return NewWriterSize(w, defaultBufSize)
   602  }
   603  
   604  // Size returns the size of the underlying buffer in bytes.
   605  func (b *Writer) Size() int { return len(b.buf) }
   606  
   607  // Reset discards any unflushed buffered data, clears any error, and
   608  // resets b to write its output to w.
   609  // Calling Reset on the zero value of Writer initializes the internal buffer
   610  // to the default size.
   611  func (b *Writer) Reset(w io.Writer) {
   612  	if b.buf == nil {
   613  		b.buf = make([]byte, defaultBufSize)
   614  	}
   615  	b.err = nil
   616  	b.n = 0
   617  	b.wr = w
   618  }
   619  
   620  // Flush writes any buffered data to the underlying io.Writer.
   621  func (b *Writer) Flush() error {
   622  	if b.err != nil {
   623  		return b.err
   624  	}
   625  	if b.n == 0 {
   626  		return nil
   627  	}
   628  	n, err := b.wr.Write(b.buf[0:b.n])
   629  	if n < b.n && err == nil {
   630  		err = io.ErrShortWrite
   631  	}
   632  	if err != nil {
   633  		if n > 0 && n < b.n {
   634  			copy(b.buf[0:b.n-n], b.buf[n:b.n])
   635  		}
   636  		b.n -= n
   637  		b.err = err
   638  		return err
   639  	}
   640  	b.n = 0
   641  	return nil
   642  }
   643  
   644  // Available returns how many bytes are unused in the buffer.
   645  func (b *Writer) Available() int { return len(b.buf) - b.n }
   646  
   647  // AvailableBuffer returns an empty buffer with b.Available() capacity.
   648  // This buffer is intended to be appended to and
   649  // passed to an immediately succeeding Write call.
   650  // The buffer is only valid until the next write operation on b.
   651  func (b *Writer) AvailableBuffer() []byte {
   652  	return b.buf[b.n:][:0]
   653  }
   654  
   655  // Buffered returns the number of bytes that have been written into the current buffer.
   656  func (b *Writer) Buffered() int { return b.n }
   657  
   658  // Write writes the contents of p into the buffer.
   659  // It returns the number of bytes written.
   660  // If nn < len(p), it also returns an error explaining
   661  // why the write is short.
   662  func (b *Writer) Write(p []byte) (nn int, err error) {
   663  	for len(p) > b.Available() && b.err == nil {
   664  		var n int
   665  		if b.Buffered() == 0 {
   666  			// Large write, empty buffer.
   667  			// Write directly from p to avoid copy.
   668  			n, b.err = b.wr.Write(p)
   669  		} else {
   670  			n = copy(b.buf[b.n:], p)
   671  			b.n += n
   672  			b.Flush()
   673  		}
   674  		nn += n
   675  		p = p[n:]
   676  	}
   677  	if b.err != nil {
   678  		return nn, b.err
   679  	}
   680  	n := copy(b.buf[b.n:], p)
   681  	b.n += n
   682  	nn += n
   683  	return nn, nil
   684  }
   685  
   686  // WriteByte writes a single byte.
   687  func (b *Writer) WriteByte(c byte) error {
   688  	if b.err != nil {
   689  		return b.err
   690  	}
   691  	if b.Available() <= 0 && b.Flush() != nil {
   692  		return b.err
   693  	}
   694  	b.buf[b.n] = c
   695  	b.n++
   696  	return nil
   697  }
   698  
   699  // WriteRune writes a single Unicode code point, returning
   700  // the number of bytes written and any error.
   701  func (b *Writer) WriteRune(r rune) (size int, err error) {
   702  	// Compare as uint32 to correctly handle negative runes.
   703  	if uint32(r) < utf8.RuneSelf {
   704  		err = b.WriteByte(byte(r))
   705  		if err != nil {
   706  			return 0, err
   707  		}
   708  		return 1, nil
   709  	}
   710  	if b.err != nil {
   711  		return 0, b.err
   712  	}
   713  	n := b.Available()
   714  	if n < utf8.UTFMax {
   715  		if b.Flush(); b.err != nil {
   716  			return 0, b.err
   717  		}
   718  		n = b.Available()
   719  		if n < utf8.UTFMax {
   720  			// Can only happen if buffer is silly small.
   721  			return b.WriteString(string(r))
   722  		}
   723  	}
   724  	size = utf8.EncodeRune(b.buf[b.n:], r)
   725  	b.n += size
   726  	return size, nil
   727  }
   728  
   729  // WriteString writes a string.
   730  // It returns the number of bytes written.
   731  // If the count is less than len(s), it also returns an error explaining
   732  // why the write is short.
   733  func (b *Writer) WriteString(s string) (int, error) {
   734  	nn := 0
   735  	for len(s) > b.Available() && b.err == nil {
   736  		n := copy(b.buf[b.n:], s)
   737  		b.n += n
   738  		nn += n
   739  		s = s[n:]
   740  		b.Flush()
   741  	}
   742  	if b.err != nil {
   743  		return nn, b.err
   744  	}
   745  	n := copy(b.buf[b.n:], s)
   746  	b.n += n
   747  	nn += n
   748  	return nn, nil
   749  }
   750  
   751  // ReadFrom implements io.ReaderFrom. If the underlying writer
   752  // supports the ReadFrom method, this calls the underlying ReadFrom.
   753  // If there is buffered data and an underlying ReadFrom, this fills
   754  // the buffer and writes it before calling ReadFrom.
   755  func (b *Writer) ReadFrom(r io.Reader) (n int64, err error) {
   756  	if b.err != nil {
   757  		return 0, b.err
   758  	}
   759  	readerFrom, readerFromOK := b.wr.(io.ReaderFrom)
   760  	var m int
   761  	for {
   762  		if b.Available() == 0 {
   763  			if err1 := b.Flush(); err1 != nil {
   764  				return n, err1
   765  			}
   766  		}
   767  		if readerFromOK && b.Buffered() == 0 {
   768  			nn, err := readerFrom.ReadFrom(r)
   769  			b.err = err
   770  			n += nn
   771  			return n, err
   772  		}
   773  		nr := 0
   774  		for nr < maxConsecutiveEmptyReads {
   775  			m, err = r.Read(b.buf[b.n:])
   776  			if m != 0 || err != nil {
   777  				break
   778  			}
   779  			nr++
   780  		}
   781  		if nr == maxConsecutiveEmptyReads {
   782  			return n, io.ErrNoProgress
   783  		}
   784  		b.n += m
   785  		n += int64(m)
   786  		if err != nil {
   787  			break
   788  		}
   789  	}
   790  	if err == io.EOF {
   791  		// If we filled the buffer exactly, flush preemptively.
   792  		if b.Available() == 0 {
   793  			err = b.Flush()
   794  		} else {
   795  			err = nil
   796  		}
   797  	}
   798  	return n, err
   799  }
   800  
   801  // buffered input and output
   802  
   803  // ReadWriter stores pointers to a Reader and a Writer.
   804  // It implements io.ReadWriter.
   805  type ReadWriter struct {
   806  	*Reader
   807  	*Writer
   808  }
   809  
   810  // NewReadWriter allocates a new ReadWriter that dispatches to r and w.
   811  func NewReadWriter(r *Reader, w *Writer) *ReadWriter {
   812  	return &ReadWriter{r, w}
   813  }
   814  

View as plain text