...

Source file src/bufio/bufio.go

Documentation: bufio

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

View as plain text