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

View as plain text