美文网首页
golang-bytes buffer 包

golang-bytes buffer 包

作者: dongfanliang | 来源:发表于2016-12-21 20:02 被阅读534次

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) {}

相关文章

网友评论

      本文标题:golang-bytes buffer 包

      本文链接:https://www.haomeiwen.com/subject/azaqvttx.html