Golang bytesパッケージBufferソース分析

17247 ワード

bytes/buffer.go
Bufferは、[]byteをカプセル化し、読み書き機能を提供する拡張可能なバイトバッファを提供します.
 
こうぞうたい
type Buffer struct {
   buf       []byte   // contents are the bytes buf[off : len(buf)]   
   off       int      // read at &buf[off], write at &buf[len(buf)]   , 
   bootstrap [64]byte // memory to hold first slice; helps small buffers avoid allocation.   , 
   lastRead  readOp   // last read operation, so that Unread* can work correctly. , UnReadRune , , 

   // FIXME: it would be advisable to align Buffer to cachelines to avoid false
   // sharing.
}

Bufferは、ReadメソッドとWriteメソッドを持つ可変サイズのバイトバッファです.Bufferのゼロ値は、使用可能な空のバッファです.
 
初期化
func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }

bufに基づいてbufferバッファを初期化
 
func NewBufferString(s string) *Buffer {
   return &Buffer{buf: []byte(s)}
}

文字列に基づいてbufferを初期化して返します
 
readOp定数は、バッファに対して実行される最後の動作を記述する
type readOp int8

// Don't use iota for these, as the values need to correspond with the
// names and comments, which is easier to see when being explicit.
const (
   opRead      readOp = -1 // Any other read operation.   
   opInvalid   readOp = 0  // Non-read operation.     
   opReadRune1 readOp = 1  // Read rune of size 1.   1  ( UTF-8 1-4 )
   opReadRune2 readOp = 2  // Read rune of size 2.   2 
   opReadRune3 readOp = 3  // Read rune of size 3.   3 
   opReadRune4 readOp = 4  // Read rune of size 4.   4 
)

 
func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }

≪アクション|Actions|emdw≫:未読部分を取得するbufferデータBytesは、バッファの未読部分を含む長さb.Len()のセグメントを返します.スライスは、次のバッファが変更される前にのみ有効です(つまり、次のRead、Write、Reset、Truncateのようなメソッドが呼び出されるまで).
 
func (b *Buffer) String() string {
   if b == nil {
      // Special case, useful in debugging.
      return ""
   }
   return string(b.buf[b.off:])
}

≪アクション|Actions|emdw≫:バッファ内の未読部分の文字列形式を返します.
 
// empty returns whether the unread portion of the buffer is empty.
func (b *Buffer) empty() bool { return len(b.buf) <= b.off }

≪アクション|Action|emdw≫:バッファの未読部分が空であるかどうかを返します.
 
//Len returns the number of bytes of the unread portion of the buffer;
func (b *Buffer) Len() int { return len(b.buf) - b.off }

≪アクション|Actions|emdw≫:バッファの未読部分のバイト数を返します.
 
// Cap returns the capacity of the buffer's underlying byte slice, that is, the
// total space allocated for the buffer's data.
func (b *Buffer) Cap() int { return cap(b.buf) }

≪アクション|Actions|emdw≫:バッファ・スライスの容量、すなわちバッファ・データに割り当てられた合計領域を返します.
 
// Truncate discards all but the first n unread bytes from the buffer
// but continues to use the same allocated storage.
// It panics if n is negative or greater than the length of the buffer.
func (b *Buffer) Truncate(n int) {
   if n == 0 {
      b.Reset()
      return
   }
   b.lastRead = opInvalid
   if n < 0 || n > b.Len() {
      panic("bytes.Buffer: truncation out of range")
   }
   b.buf = b.buf[:b.off+n]
}

≪アクション|Action|emdw≫:バッファから前のn個の未読バイトを除くすべてのバイトを破棄しますが、同じ割り当てられたストレージを使用し続けます.(読み込まれたデータは削除されません)nが負またはバッファの長さより大きい場合、panicが発生します.
 
// Reset resets the buffer to be empty,
// but it retains the underlying storage for use by future writes.
// Reset is the same as Truncate(0).
func (b *Buffer) Reset() {
   b.buf = b.buf[:0]
   b.off = 0
   b.lastRead = opInvalid
}

操作のリセット
バッファを空にリセットしますが、将来の書き込みのために最下位のストレージが保持されます.(データクリア、cap不変)offsetオフセット量0 lastRead未読み出し
 
// tryGrowByReslice is a inlineable version of grow for the fast-case where the
// internal buffer only needs to be resliced.
// It returns the index where bytes should be written and whether it succeeded.
// 。
//  。
//   ( len(b.off)+n < c )
func (b *Buffer) tryGrowByReslice(n int) (int, bool) {
	if l := len(b.buf); n <= cap(b.buf)-l {
		b.buf = b.buf[:l+n]
		return l, true
	}
   return 0,false
}

 
// grow grows the buffer to guarantee space for n more bytes.
// It returns the index where bytes should be written.
// If the buffer can't grow it will panic with ErrTooLarge.
func (b *Buffer) grow(n int) int {
   m := b.Len()
   // If buffer is empty, reset to recover space.
   if m == 0 && b.off != 0 {
      b.Reset()
   }
   // Try to grow by means of a reslice.
   if i, ok := b.tryGrowByReslice(n); ok {
      return i
   }
   // Check if we can make use of bootstrap array.
   if b.buf == nil && n <= len(b.bootstrap) {
      b.buf = b.bootstrap[:n]
      return 0
   }
   c := cap(b.buf)
   if n <= c/2-m {
      // We can slide things down instead of allocating a new
      // slice. We only need m+n <= c to slide, but
      // we instead let capacity get twice as large so we
      // don't spend all our time copying.
      copy(b.buf, b.buf[b.off:])
   } else if c > maxInt-c-n {
      //panic(ErrTooLarge)
   } else {
      // Not enough space anywhere, we need to allocate.
      buf := makeSlice(2*c + n)
      copy(buf, b.buf[b.off:])
      b.buf = buf
   }
   // Restore b.off and len(b.buf).
   b.off = 0
   b.buf = b.buf[:m+n]
   return m
}

≪アクション|Actions|emdw≫:バッファ拡張に使用されるnバイトの長さ.バイトに書き込むインデックスを返します.拡張規則は次のとおりです.
1.len(n.buf)+n<=cap(b.buf)は直接b.buf[:len(b.buf)+n]2を返す.b.buf==nil&&n<=len(b.bootstrap)は直接b.bootstrap[:n]3に戻る.n+m<=c/2(mは未読の長さ、cは容量)では、スライドcopy(b.buf,b.buf[b.off:])を行い、既読部分を除去する.buf:=makeSlice(2*c+n)、容量プログラミング2*c+n、即時元の容量の2倍+n
 
// makeSlice allocates a slice of size n. If the allocation fails, it panics
// with ErrTooLarge.
func makeSlice(n int) []byte {
   // If the make fails, give a known error.
   defer func() {
      if recover() != nil {
         panic(ErrTooLarge)
      }
   }()
   return make([]byte, n)
}

スライスサイズnのスライスを割り当てます.
 
// Grow grows the buffer's capacity, if necessary, to guarantee space for
// another n bytes. After Grow(n), at least n bytes can be written to the
// buffer without another allocation.
// If n is negative, Grow will panic.
// If the buffer can't grow it will panic with ErrTooLarge.
func (b *Buffer) Grow(n int) {
   if n < 0 {
      panic("bytes.Buffer.Grow: negative count")
   }
   m := b.grow(n)
   b.buf = b.buf[:m]
}

必要に応じて、Growはバッファの容量を増加させ、他のnバイトの空間を保証します.grow()を呼び出して拡張する
 
// Write appends the contents of p to the buffer, growing the buffer as
// needed. The return value n is the length of p; err is always nil. If the
// buffer becomes too large, Write will panic with ErrTooLarge.
func (b *Buffer) Write(p []byte) (n int, err error) {
   b.lastRead = opInvalid
   //ok ,m 
   m, ok := b.tryGrowByReslice(len(p))
   if !ok {
      // ,m 
      m = b.grow(len(p))
   }
   return copy(b.buf[m:], p), nil
}

作用:スライスpの内容をbufferバッファに書く
 
// WriteString appends the contents of s to the buffer, growing the buffer as
// needed. The return value n is the length of s; err is always nil. If the
// buffer becomes too large, WriteString will panic with ErrTooLarge.
func (b *Buffer) WriteString(s string) (n int, err error) {
   b.lastRead = opInvalid
   m, ok := b.tryGrowByReslice(len(s))
   if !ok {
      m = b.grow(len(s))
   }
   return copy(b.buf[m:], s), nil
}

役割:文字列sをバッファbufferに書き込む
 
// MinRead is the minimum slice size passed to a Read call by
// Buffer.ReadFrom. As long as the Buffer has at least MinRead bytes beyond
// what is required to hold the contents of r, ReadFrom will not grow the
// underlying buffer.
//MinRead Buffer.ReadFrom Read 。
//  Buffer r MinRead ,ReadFrom 。
const MinRead = 512


// ReadFrom reads data from r until EOF and appends it to the buffer, growing
// the buffer as needed. The return value n is the number of bytes read. Any
// error except io.EOF encountered during the read is also returned. If the
// buffer becomes too large, ReadFrom will panic with ErrTooLarge.
func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {
   b.lastRead = opInvalid
   for {
      i := b.grow(MinRead)
      m, e := r.Read(b.buf[i:cap(b.buf)])
      if m < 0 {
         panic(errNegativeRead)
      }

      b.buf = b.buf[:i+m]
      n += int64(m)
      if e == io.EOF {
         return n, nil // e is EOF, so return nil explicitly
      }
      if e != nil {
         return n, e
      }
   }
}

役割:ReadFromは、rからEOFまでデータを読み込み、必要に応じてバッファに自動的に拡張します.戻り値nは、読み出したバイト数である.読み出し中に遭遇するioを除く.EOF以外のエラーも返されます.バッファが大きすぎるとReadFromがErrTooLarge panicをトリガーする可能性があります
 
// WriteTo writes data to w until the buffer is drained or an error occurs.
// The return value n is the number of bytes written; it always fits into an
// int, but it is int64 to match the io.WriterTo interface. Any error
// encountered during the write is also returned.
func (b *Buffer) WriteTo(w io.Writer) (n int64, err error) {
   b.lastRead = opInvalid
   if nBytes := b.Len(); nBytes > 0 {
      m, e := w.Write(b.buf[b.off:])
      if m > nBytes {
         panic("bytes.Buffer.WriteTo: invalid Write count")
      }
      b.off += m
      n = int64(m)
      if e != nil {
         return n, e
      }
      // all bytes should have been written, by definition of
      // Write method in io.Writer
      if m != nBytes {
         return n, io.ErrShortWrite
      }
   }
   // Buffer is now empty; reset.
   b.Reset()
   return n, nil
}

WriteToメソッドは、バッファが枯渇したりエラーが発生したりするまで、バッファのデータをwに書き込む.戻り値nは書き込みバイト数である.常にintに適していますが、ioに一致するようにint 64です.WriterToインタフェース.書き込み中に発生したエラーも返されます.
 
// WriteByte appends the byte c to the buffer, growing the buffer as needed.
// The returned error is always nil, but is included to match bufio.Writer's
// WriteByte. If the buffer becomes too large, WriteByte will panic with
// ErrTooLarge.
func (b *Buffer) WriteByte(c byte) error {
   b.lastRead = opInvalid
   m, ok := b.tryGrowByReslice(1)
   if !ok {
      m = b.grow(1)
   }
   b.buf[m] = c
   return nil
}

WriteByteはバイトcをバッファに付加し,必要に応じてバッファを自動的に拡張する.返されるエラーは常にnilであり、バッファが大きすぎてErrTooLargeを超えるとpanicが発生します.
 
// WriteRune appends the UTF-8 encoding of Unicode code point r to the
// buffer, returning its length and an error, which is always nil but is
// included to match bufio.Writer's WriteRune. The buffer is grown as needed;
// if it becomes too large, WriteRune will panic with ErrTooLarge.
func (b *Buffer) WriteRune(r rune) (n int, err error) {
   //r , WriteByte
   if r < utf8.RuneSelf {
      b.WriteByte(byte(r))
      return 1, nil
   }
   // , ,r utf8.UTFMax( 4 )
   b.lastRead = opInvalid
   m, ok := b.tryGrowByReslice(utf8.UTFMax)
   if !ok {
      m = b.grow(utf8.UTFMax)
   }
   // r 
   n = utf8.EncodeRune(b.buf[m:m+utf8.UTFMax], r)
   b.buf = b.buf[:m+n]
   return n, nil
}

WriteRuneはUnicode文字rのUTF-8符号化をバッファに付加し、その長さとエラーを返します.バッファがErrTooLargeを大きく超えすぎるとpanicが発生します.
 
// Read reads the next len(p) bytes from the buffer or until the buffer
// is drained. The return value n is the number of bytes read. If the
// buffer has no data to return, err is io.EOF (unless len(p) is zero);
// otherwise it is nil.
func (b *Buffer) Read(p []byte) (n int, err error) {
   b.lastRead = opInvalid
   // 
   if b.empty() {
      // Buffer is empty, reset to recover space.
      b.Reset()
      if len(p) == 0 {
         return 0, nil
      }
      return 0, io.EOF
   }
   // cope p
   n = copy(p, b.buf[b.off:])
   b.off += n
   if n > 0 {
      b.lastRead = opRead
   }
   return n, nil
}

役割:バッファからlen(p)バイトをpスライスに読み出し、バッファ内の残りの要素の数がlen(p)より小さい場合、バッファ内の残りの要素をpスライスに読み出す.戻り値nは、読み出したバイト数である.バッファにデータがない場合、errはioである.EOF(len(p)がゼロでない限り).さもないとnilです.
 
// Next returns a slice containing the next n bytes from the buffer,
// advancing the buffer as if the bytes had been returned by Read.
// If there are fewer than n bytes in the buffer, Next returns the entire buffer.
// The slice is only valid until the next call to a read or write method.
func (b *Buffer) Next(n int) []byte {
   b.lastRead = opInvalid
   // buffer m
   m := b.Len()
   if n > m {
      n = m
   }

   data := b.buf[b.off : b.off+n]
   b.off += n
   if n > 0 {
      b.lastRead = opRead
   }
   return data
}

Nextは、バッファ内の次のn個の未読バイトを取得し、Readがデータを読み出すようにバッファのポインタオフセットoffを移動するために使用される.バッファ内のバイトがn個未満の場合、Nextはバッファ全体を返します.スライスは、次のreadメソッドまたはwriteメソッドを呼び出す前にのみ有効です.Nextは、ポインタオフセットが増加するため、読み取り操作にも属します.
// ReadByte reads and returns the next byte from the buffer.
// If no byte is available, it returns error io.EOF.
func (b *Buffer) ReadByte() (byte, error) {
   // , , io.EOF
   if b.empty() {
      // Buffer is empty, reset to recover space.
      b.Reset()
      return 0, io.EOF
   }
   // , +1, opRead 
   c := b.buf[b.off]
   b.off++
   b.lastRead = opRead
   return c, nil
}

読み出しバッファの次の未読み出しバイトは、読み出し可能なバイトがない場合にバッファをリセットするioを返す.EOF
 
// ReadRune reads and returns the next UTF-8-encoded
// Unicode code point from the buffer.
// If no bytes are available, the error returned is io.EOF.
// If the bytes are an erroneous UTF-8 encoding, it
// consumes one byte and returns U+FFFD, 1.
func (b *Buffer) ReadRune() (r rune, size int, err error) {
   // 
   if b.empty() {
      // Buffer is empty, reset to recover space.
      b.Reset()
      return 0, 0, io.EOF
   }
   // ASCII,
   c := b.buf[b.off]
   if c < utf8.RuneSelf {
      b.off++
      b.lastRead = opReadRune1
      return rune(c), 1, nil
   }
   // utf-8 ,r ,n 
   r, n := utf8.DecodeRune(b.buf[b.off:])
   b.off += n
   b.lastRead = readOp(n)
   return r, n, nil
}

utf-8文字を読み出し、f文字と文字の長さsizeを返します.
// UnreadRune unreads the last rune returned by ReadRune.
// If the most recent read or write operation on the buffer was
// not a successful ReadRune, UnreadRune returns an error.  (In this regard
// it is stricter than UnreadByte, which will unread the last byte
// from any read operation.)
func (b *Buffer) UnreadRune() error {
   // ReadRune(), 
   if b.lastRead <= opInvalid {
      return errors.New("bytes.Buffer: UnreadRune: previous operation was not a successful ReadRune")
   }

   // off ReadRune 
   if b.off >= int(b.lastRead) {
      b.off -= int(b.lastRead)
   }
   b.lastRead = opInvalid
   return nil
}

UnreadRuneメソッドは、前回のReadRune操作のデータを撤回するために使用され、前回の操作がReadRune()でない場合はエラーを返します.
 
// UnreadByte unreads the last byte returned by the most recent successful
// read operation that read at least one byte. If a write has happened since
// the last read, if the last read returned an error, or if the read read zero
// bytes, UnreadByte returns an error.
func (b *Buffer) UnreadByte() error {
   if b.lastRead == opInvalid {
      return errors.New("bytes.Buffer: UnreadByte: previous operation was not a successful read")
   }
   b.lastRead = opInvalid
   if b.off > 0 {
      b.off--
   }
   return nil
}

UnreadByteメソッドは、前回のReadByteデータを取り消し、前回がReadByte()でない場合はエラーを返します.
 
// ReadBytes reads until the first occurrence of delim in the input,
// returning a slice containing the data up to and including the delimiter.
// If ReadBytes encounters an error before finding a delimiter,
// it returns the data read before the error and the error itself (often io.EOF).
// ReadBytes returns err != nil if and only if the returned data does not end in
// delim.
func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) {
   slice, err := b.readSlice(delim)
   // return a copy of slice. The buffer's backing array may
   // be overwritten by later calls.
   line = append(line, slice...)
   return line, err
}

ReadBytesメソッドは、delimバイトが最初に現れるまで読み取り、delimが残りのbufferにない場合は読み取り終了します.
 
// readSlice is like ReadBytes but returns a reference to internal buffer data.
func (b *Buffer) readSlice(delim byte) (line []byte, err error) {
   i := IndexByte(b.buf[b.off:], delim)
   end := b.off + i + 1
   if i < 0 {
      //len(b.buf) 
      end = len(b.buf)
      err = io.EOF
   }
   line = b.buf[b.off:end]
   b.off = end
   b.lastRead = opRead
   return line, err
}

バッファの残りのデータを読み出し、delimバイトまでdelimバイトが見つからない場合、残りのすべてのデータをReadBytesとは異なりreadSliceがbufferデータの参照を直接返す
 
// ReadString reads until the first occurrence of delim in the input,
// returning a string containing the data up to and including the delimiter.
// If ReadString encounters an error before finding a delimiter,
// it returns the data read before the error and the error itself (often io.EOF).
// ReadString returns err != nil if and only if the returned data does not end
// in delim.
func (b *Buffer) ReadString(delim byte) (line string, err error) {
   slice, err := b.readSlice(delim)
   return string(slice), err
}

ReadStringメソッドはReadBytes機能と似ていますが、文字列を返すだけです.