Golang bytes.Buffer源码分析
Buffer作为高效缓存支持读、写与撤销读取操作,可用于字节流缓存与解析等。这里简要分析一下其源码实现。
本文源码版本为go1.16.3 linux/amd64
自增长规则
Buffer可以在长度不足时增加自身长度,其核心增长函数是grow(n int) int
私有函数,源码在go/src/bytes/buffer.go
第117行:
// 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
}
if b.buf == nil && n <= smallBufferSize {
b.bu