Golang bytes包Buffer源码分析

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:] }

作用:用于获取未读部分的buffer数据
Bytes返回一个长度为b.Len()的片段,其中包含缓冲区的未读部分。
切片仅在下一次缓冲区修改之前有效(即,直到下一次调用Read,Write,Reset或Truncate之类的方法)。

 

func (b *Buffer) String() string {
   if b == nil {
      // Special case, useful in debugging.
      return "<nil>"
   }
   return string(b.buf[b.off:])
}

作用:返回缓冲区中未读部分的字符串形式

 

// empty returns whether the unread portion of the buffer is empty.
func (b *Buffer) empty() bool { return len(b.buf) <= b.off }

作用:返回缓冲区的未读部分是否为空

 

//Len returns the number of bytes of the unread portion of the buffer;
func (b *Buffer) Len() int { return len(b.buf) - b.off }

作用:返回缓冲区未读部分的字节数;

 

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

作用:返回缓冲区切片的容量,即为缓冲区数据分配的总空间。

 

// 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
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值