美文网首页
bytes.Buffer 代码阅读

bytes.Buffer 代码阅读

作者: wayyyy | 来源:发表于2022-04-10 01:49 被阅读0次

bytes.Buffer 是一个缓冲byte类型的缓冲器:

image.png
const smallBufferSize = 64

type Buffer struct {
    buf []byte    // contents are the bytes buf[off : len(buf)]
    off int    // read at &buf[off], write at &buf[len(buf)]
    lastRead readop  // last read operation, so that Unread* can work correctly
}

type readOp int8

const (
    opRead      readOp = -1 // Any other read operation.
    opInvalid   readOp = 0  // Non-read operation.
    opReadRune1 readOp = 1  // Read rune of size 1.
    opReadRune2 readOp = 2  // Read rune of size 2.
    opReadRune3 readOp = 3  // Read rune of size 3.
    opReadRune4 readOp = 4  // Read rune of size 4.
)

var ErrTooLarge = errors.New("bytes.Buffer: too large")
var errNegativeRead = errors.New("bytes.Buffer: reader returned negative count from Read")

const maxInt = int(^uint(0) >> 1)
创建

使用:

buf1 := bytes.NewBufferString("hello")
buf2 := bytes.NewBuffer([]byte("hello"))
buf3 := bytes.NewBuffer([]byte{'h','e','l','l','o'})

源码:

func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }

func NewBufferString(s string) *Buffer {
    return &Buffer{buf: []byte(s)}
}
写入
读取
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
    }
    n = copy(p, b.buf[b.off:])
    b.off += n
    if n > 0 {
        b.lastRead = opRead
    }
    return n, nil
}
func (b *Buffer) ReadByte() (byte, error) {
    if b.empty() {
        // Buffer is empty, reset to recover space.
        b.Reset()
        return 0, io.EOF
    }
    c := b.buf[b.off]
    b.off++
    b.lastRead = opRead
    return c, nil
}

var errUnreadByte = errors.New("bytes.Buffer: UnreadByte: previous operation was not a successful read")
func (b *Buffer) UnreadByte() error {
    if b.lastRead == opInvalid {
        return errUnreadByte
    }
    b.lastRead = opInvalid
    if b.off > 0 {
        b.off--
    }
    return nil
}

其他还有类似:ReadRuneUnReadRune

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
}

相关文章

网友评论

      本文标题:bytes.Buffer 代码阅读

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