golang-bytes buffer 包

buffer包的原型

// A Buffer is a variable-sized buffer of bytes with Read and Write methods.
// The zero value for Buffer is an empty buffer ready to use.
type Buffer struct {
    buf       []byte            // contents are the bytes buf[off : len(buf)]
    off       int               // read at &buf[off], write at &buf[len(buf)]
    runeBytes [utf8.UTFMax]byte // avoid allocation of slice on each WriteByte or Rune
    bootstrap [64]byte          // memory to hold first slice; helps small buffers (Printf) avoid allocation.
    lastRead  readOp            // last read operation, so that Unread* can work correctly.
}

方法函数

// 返回buffer字节     
func (b *Buffer) Bytes() []byte {}   
// 返回字符串, 内部调用Bytes方法
func (b *Buffer) String() string {}
// 返回buffer长度
func (b *Buffer) Len() int {}
// 截断buffer
func (b *Buffer) Truncate(n int) {}
//重置buffer
func (b *Buffer) Reset() { b.Truncate(0) }
// buffer扩容,内部调用grow, 对外函数
func (b *Buffer) Grow(n int) {}
// buffer扩容 
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.Truncate(0)
    }
    if len(b.buf)+n > cap(b.buf) {
        var buf []byte
        if b.buf == nil && n <= len(b.bootstrap) {
            buf = b.bootstrap[0:]
        } else if m+n <= cap(b.buf)/2 {
            // We can slide things down instead of allocating a new
            // slice. We only need m+n <= cap(b.buf) 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:])
            buf = b.buf[:m]
        } else {
            // not enough space anywhere
            buf = makeSlice(2*cap(b.buf) + n)  // 重新申请内存
            copy(buf, b.buf[b.off:])
        }
        b.buf = buf
        b.off = 0
    }
    b.buf = b.buf[0 : b.off+m+n]
    return b.off + m
}
// 写函数
func (b *Buffer) Write(p []byte) (n int, err error) {
    b.lastRead = opInvalid
    m := b.grow(len(p))
    return copy(b.buf[m:], p), nil
}
// 同上
func (b *Buffer) WriteString(s string) (n int, err error) {}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容