Golang Bytes Buffer Code anatomy

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
Data structure, bytes buffertype buffer struct {buf       [] Byte            // byte slicing off        int                //  Write Data Runebytes [utf8 from &buf[off] address read data,  from &buf[len (BUF)] address. Utfmax]byte // avoid allocation of slice on each writebyte or  runebootstrap [64]byte          // memory  to hold first slice; helps small buffers  (Printf)  avoid  allocation.lastread  readop            / / last read operation, so that unread* can work correctly.}

Let's see how write is implemented in bytes buffer.

Func (b *buffer) writestring (s string) (n int, err error) {B.lastread = opinvalid//Non-read operation does not require read flag equals 0m: = b . Grow (Len (s))//growth size (accurately adjusted data in buf position, does not necessarily grow), M is of course old data end return copy (B.buf[m:], s), nil//copy data, starting from M}

The most important thing to see.

func  (B *buffer)  grow (n int)  int {m := b.len ()  //func  (b  *buffer)  len ()  int { return len (B.BUF)  - b.off }//  M is buf len  minus (-)  b.off (read start position) if m == 0 && b.off != 0  {b.truncate (0)  //below gives display} //resizing and positioning If len (B.BUF) +n > cap (B.BUF)  {var  buf []byteif b.buf == nil && n <= len (B.bootstrap)  {buf = b.bootstrap[0:] //This bootstrap caches buf slices, which is said to prevent heavy allocation} else if m+n  <= cap (B.BUF)/2 { //  twice times the principle of applying for a new slice copy (B.buf[:], b.buf[b.off:]) buf =  b.buf[:m]} else {// not enough space anywherebuf = makeslice ( Cap (B.BUF)  + n) copy (Buf, b.buf[b.off:])}b.buf = bufb.off = 0}b.buf =  b.buf[0 : b.off+m+n] //Assignment Return b.off + m} 

And look at the function truncate it used, cut the slices.

Func (b *buffer) Truncate (n int) {B.lastread = Opinvalidswitch {case N < 0 | | n > B.len ():p anic ("bytes. Buffer:truncation out of a range ") case n = = 0://Reuse buffer Space.b.off = 0}B.BUF = B.buf[0:b.off+n]}

Makeslice function

Func makeslice (n int) []byte {//If the make fails, give a known error.defer func () {If recover ()! = nil {Panic (errtoolarg e)}} () return make ([]byte, N)//actually call this make}

Finally take a look at a usage example

Package Mainimport ("bytes" "FMT" "StrConv" "Time") Func main () {var buffer bytes. Bufferttime: = time. Now (). Unixnano () for I: = 0; i < 10000000; i++ {buffer. WriteString (StrConv. Itoa (i))}ttime1: = time. Now (). Unixnano ()//take content buffer. Bytes () or buffer. String () fmt. Printf ("Time Cal%f%d\n", Float64 (ttime1-ttime)/float64 (1*time. Second), Len (buffer. String ()))}

Summary: Bytes Buffer: A container that writes a byte or string of strings

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.