Golang's Bytes.buffer study notes

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The Bytes.buffer is a buffer of type byte which is stored in byte
Buffer is a type buffer struct{in the bytes package ...}

A buffer is a variable-sized buffer of bytes with Read and Write methods. The zero value for Buffer is a empty Buffer ready-to-use.
(is a variable-length buffer with the Read and write methods.) The 0 value of buffer is an empty buffer, but can be used)
Buffer is like a container container that can store things and fetch things (Access data)
Create a Buffer (in fact the bottom is a []byte, byte slice)
Write data to (write Mtheods)
Read data from (Write methods)

Creating buffer Buffers

var b bytes. Buffer//directly define a buffer variable without initialization
B.writer ([]byte ("Hello"))//can be used directly

B1: = new (bytes. Buffer)//directly using the new initialization, you can use the
Two other ways to define
Func Newbuffer (buf []byte) *buffer
Func newbufferstring (s string) *buffer

Newbuffer

//Newbuffer creates and initializes a new Buffer using BUF as its initial
//contents. It is intended to prepare a Buffer to read existing data. It
//can also is used to size the internal buffer for writing. To does that, the
//BUF should has the desired capacity but a length of zero.
//
//In the most cases, new (buffer) (or just declaring a buffer variable) is
//sufficient to initialize a buffer .
Func newbuffer (buf []byte) *buffer {return &buffer{buf:buf}}
Newbuffer initializes Buffer with BUF as a parameter,
Buffer can be read or written
if it is read buffer,buf need to fill certain data
If it is write, buf need to have a certain capacity (capacity), of course, you can also initialize buffer through new (buffer). Another method newbufferstring uses a string to initialize the readable buffer, and fills the buffer with the contents of the string.
Func inttobytes (n int) []byte {
X: = Int32 (n)
//Create a content that is []byte slice buffer
//with bytes. Newbufferstring ("") equivalent
Bytesbuffer: = bytes. Newbuffer ([]byte{})
Binary. Write (Bytesbuffer, Binary. Bigendian, x)
return bytesbuffer.bytes ()
}

Newbufferstring

The Newbufferstring method initializes the readable buffer with a string and fills the buffer with the contents of the string.
There's no big difference between usage and newbuffer.
Newbufferstring creates and initializes a new Buffer using string s as its
Initial contents. It's intended to prepare a buffer to read a existing
String.
//
In the most cases, new (buffer) (or just declaring a buffer variable) is
Sufficient to initialize a Buffer.
Func newbufferstring (s string) *buffer {
return &BUFFER{BUF: []byte (s)}
}
Func testbufferstring () {
Buf1:=bytes. Newbufferstring ("Swift")
Buf2:=bytes. Newbuffer ([]byte ("Swift"))
Buf3:=bytes. Newbuffer ([]byte{' s ', ' w ', ' I ', ' f ', ' t '})
Fmt. Println ("=========== below buf1,buf2,buf3 equivalent =========")
Fmt. Println ("Buf1:", BUF1)
Fmt. Println ("Buf2:", BUF2)
Fmt. Println ("Buf3:", BUF3)
Fmt. Println ("=========== below creates an empty buffer equivalent =========")
Buf4:=bytes. Newbufferstring ("")
Buf5:=bytes. Newbuffer ([]byte{})
Fmt. Println ("Buf4:", BUF4)
Fmt. Println ("Buf5:", Buf5)
}
Output:

=========== below BUF1,BUF2,BUF3 equivalent =========
Buf1:swift
Buf2:swift
Buf3:swift
=========== below creates an empty buffer equivalent =========
BUF4:
BUF5:

Writing data to Buffer

Write
Writes the byte slice p to buffer.

Write appends the contents of p to the buffer, growing the buffer as
Needed. The return value n is the length of p; Err is always nil. If the
Buffer becomes too large, Write would panic with Errtoolarge.
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
}
Fmt. Println ("=========== to write Swift to learning buffer tail ========= below")
Newbytes: = []byte ("Swift")
Create a buffer for content learning
BUF: = bytes. Newbuffer ([]byte ("Learning"))
Print as Learning
Fmt. Println (BUF. String ())
Write newbytes this slice to BUF's tail.
Buf. Write (Newbytes)
Fmt. Println (BUF. String ())
Print:

=========== writes Swift to the learning buffer tail via write =========
Learning
Learningswift
writestring
Using the WriteString method, place a string at the end of the buffer

WriteString appends the contents of S to the buffer, growing the buffer as
Needed. The return value n is the length of s; Err is always nil. If the
Buffer becomes too large, writestring'll panic with Errtoolarge.
Func (b *buffer) writestring (s string) (n int, err error) {
B.lastread = Opinvalid
M: = B.grow (len (s))
Return copy (b.buf[m:], s), nil
}
Fmt. Println ("=========== following swift into learning buffer tail ========= by WriteString")
NewString: = "Swift"
Creates a buffer of string content learning
BUF: = bytes. Newbufferstring ("learning")
Print as Learning
Fmt. Println (BUF. String ())
Write newstring this string to the tail of BUF
Buf. WriteString (newstring)
Fmt. Println (BUF. String ())
Print:

=========== writes Swift to the learning buffer tail via write =========
Learning
Learningswift
WriteByte
Put a byte type of data at the end of the buffer

WriteByte appends the byte C to the buffer, growing the buffer as needed.
The returned error is always nil and is included to match Bufio. Writer ' s
WriteByte. If the buffer becomes too large, writebyte'll panic with
Errtoolarge.
Func (b *buffer) writebyte (c byte) error {
B.lastread = Opinvalid
M: = B.grow (1)
B.BUF[M] = C
return Nil
}
Fmt. Println ("=========== below through WriteByte! Write learning Buffer tail =========")
var newbyte byte = '! '
Creates a buffer of string content learning
BUF: = bytes. Newbufferstring ("learning")
Print as Learning
Fmt. Println (BUF. String ())
Write newstring this string to the tail of BUF
Buf. WriteByte (Newbyte)
Fmt. Println (BUF. String ())
Print:

=========== follows WriteByte to write swift to learning buffer tail =========
Learning
learning!
Writerune
puts a rune type of data at the end of the buffer

//Writerune appends the UTF-8 encoding of Unicode code point R-The
//buffer, returning its length and an error , which is always nil and is the
//included to match Bufio. Writer ' s writerune. The buffer is grown as needed;
//If it becomes too large, writerune'll panic with Errtoolarge.
Func (b *buffer) Writerune (R rune) (n int, err error) {
If r < UTF8. runeself {
B.writebyte (r)
return 1, Nil
}
N = UTF8. Encoderune (b.runebytes[0:], R)
B.write (B.runebytes[0:n])
return n, Nil
}
FMT. Println ("=========== below through Writerune to" good \ "Write Learning buffer Tail =========")
var newrune = ' good '
// Creates a string content learning buffer
buf: = bytes. Newbufferstring ("learning")
//print as Learning
FMT. Println (BUF. String ())
//writes newstring This string to the tail of BUF
buf. Writerune (Newrune)
Fmt. Println (BUF. String ())
Print:

=========== the following through the Writerune to write "good" learning buffer tail =========
Learning
Learning Good
Complete Example
Package Main

Import (
"Bytes"
"Encoding/binary"
"FMT"
)

Func Main () {
Newbuffer shaping into bytes
var n int = 10000
Inttobytes: = Inttobytes (n)
Fmt. Println ("==========int to bytes========")
Fmt. Println (Inttobytes)
Newbufferstring
Testbufferstring ()
Write
Bufferwrite ()
WriteString
Bufferwritestring ()
WriteByte
Bufferwritebyte ()
Writerune
Bufferwriterune ()

}

Func inttobytes (n int) []byte {
X: = Int32 (N)
Create a buffer that is []byte's slice
With bytes. Newbufferstring ("") equivalent
Bytesbuffer: = bytes. Newbuffer ([]byte{})
Binary. Write (Bytesbuffer, Binary. Bigendian, X)
Return Bytesbuffer.bytes ()
}

Func testbufferstring () {
Buf1:=bytes. Newbufferstring ("Swift")
Buf2:=bytes. Newbuffer ([]byte ("Swift"))
Buf3:=bytes. Newbuffer ([]byte{' s ', ' w ', ' I ', ' f ', ' t '})
Fmt. Println ("=========== below buf1,buf2,buf3 equivalent =========")
Fmt. Println ("Buf1:", BUF1)
Fmt. Println ("Buf2:", BUF2)
Fmt. Println ("Buf3:", BUF3)
Fmt. Println ("=========== below creates an empty buffer equivalent =========")
Buf4:=bytes. Newbufferstring ("")
Buf5:=bytes. Newbuffer ([]byte{})
Fmt. Println ("Buf4:", BUF4)
Fmt. Println ("Buf5:", Buf5)
}

Func Bufferwrite () {
Fmt. Println ("=========== to write Swift to learning buffer tail ========= below")
Newbytes: = []byte ("Swift")
Create a buffer for content learning
BUF: = bytes. Newbuffer ([]byte ("Learning"))
Print as Learning
Fmt. Println (BUF. String ())
Write newbytes this slice to BUF's tail.
Buf. Write (Newbytes)
Fmt. Println (BUF. String ())
}

Func bufferwritestring () {
Fmt. Println ("=========== to write Swift to learning buffer tail ========= below")
NewString: = "Swift"
Creates a buffer of string content learning
BUF: = bytes. Newbufferstring ("learning")
Print as Learning
Fmt. Println (BUF. String ())
Write newstring this string to the tail of BUF
Buf. WriteString (newstring)
Fmt. Println (BUF. String ())
}

Func Bufferwritebyte () {
Fmt. Println ("=========== following swift into learning buffer tail ========= by WriteByte")
var newbyte byte = '! '
Creates a buffer of string content learning
BUF: = bytes. Newbufferstring ("learning")
Print as Learning
Fmt. Println (BUF. String ())
Write newstring this string to the tail of BUF
Buf. WriteByte (Newbyte)
Fmt. Println (BUF. String ())
}

Func Bufferwriterune () {
Fmt. Println ("=========== below through Writerune put \" good \ "Write Learning buffer tail =========")
var newrune = ' good '
Creates a buffer of string content learning
BUF: = bytes. Newbufferstring ("learning")
Print as Learning
Fmt. Println (BUF. String ())
Write newstring this string to the tail of BUF
Buf. Writerune (Newrune)
Fmt. Println (BUF. String ())
}
**

reading data to Buffer

**
Read
To the Read method a container p, after reading, p is full, the buffer correspondingly reduced, the returned n is the number of successful read

Read reads the next len (p) bytes from the buffer or until the buffer
is drained. The return value n is the number of bytes read. If the
Buffer has no data to return and err is IO. EOF (unless Len (p) is zero);
Otherwise it is nil.
Func (b *buffer) Read (P []byte) (n int, err error) {}
Func Read () {
Bufs: = bytes. Newbufferstring ("Learning swift.")
Fmt. Println (Bufs. String ())

//声明一个空的slice,容量为8l := make([]byte, 8)//把bufs的内容读入到l内,因为l容量为8,所以只读了8个过来bufs.Read(l)fmt.Println("::bufs缓冲器内容::")fmt.Println(bufs.String())//空的l被写入了8个字符,所以为 Learningfmt.Println("::l的slice内容::")fmt.Println(string(l))//把bufs的内容读入到l内,原来的l的内容被覆盖了bufs.Read(l)fmt.Println("::bufs缓冲器被第二次读取后剩余的内容::")fmt.Println(bufs.String())fmt.Println("::l的slice内容被覆盖,由于bufs只有7个了,因此最后一个g被留下来了::")fmt.Println(string(l))

}
Print:

=======read=======
Learning Swift.
:: Bufs buffer Contents::
Swift.
:: L Slice Content::
Learning
:: Bufs Buffer after the second read the remaining content::

:: Slice content of L is overwritten::
Swift.g
ReadByte
Returns the first byte of the buffer head, the first byte of the buffer head is taken off

ReadByte reads and returns the next byte from the buffer.
If no byte is available, it returns error IO. Eof.
Func (b *buffer) ReadByte () (c byte, err error) {}
Func ReadByte () {
Bufs: = bytes. Newbufferstring ("Learning swift.")
Fmt. Println (Bufs. String ())
Reads the first byte, assigns a value to B
B, _: = Bufs. ReadByte ()
Fmt. Println (Bufs. String ())
Fmt. Println (string (b))
}
Print:

=======readbyte===
Learning Swift.
Earning Swift.
L
Readrune
Readrune and ReadByte are alike.
Returns the first rune of the buffer head, the first rune of the buffer head is taken away

Readrune reads and returns the next utf-8-encoded
Unicode code point from the buffer.
If No bytes is available, the error returned is IO. Eof.
If The bytes is an erroneous UTF-8 encoding, it
Consumes one byte and returns U+FFFD, 1.
Func (b *buffer) Readrune () (R rune, size int, err error) {}
Func Readrune () {
Bufs: = bytes. Newbufferstring ("Learn swift.")
Fmt. Println (Bufs. String ())

//读取第一个rune,赋值给rr,z,_ := bufs.ReadRune()//打印中文"学",缓冲器头部第一个被拿走fmt.Println(bufs.String())//打印"学","学"作为utf8储存占3个bytefmt.Println("r=",string(r),",z=",z)

}
readbytes
Readbytes needs a byte as a delimiter, read from the buffer to find the first occurrence of the delimiter (Delim), found, the beginning of the buffer from the head to the delimiter of all the byte to return, as a byte type of slice, after returning, the buffer will also be empty part

Readbytes reads until the first occurrence of delim in the input,
Returning a slice containing the data up to and including the delimiter.
If Readbytes encounters an error before finding a delimiter,
It returns the data read before the error and the error itself (often IO. EOF).
Readbytes returns ERR! = Nil if and only if the returned data does not end in
Delim.
Func (b *buffer) readbytes (Delim byte) (line []byte, err error) {}
Func readbytes () {
Bufs: = bytes. Newbufferstring ("Now start learning swift.")
Fmt. Println (Bufs. String ())

var delim byte = 'L'line, _ := bufs.ReadBytes(delim)fmt.Println(bufs.String())fmt.Println(string(line))

}
Print:

=======readbytes==
Start learning Swift now.
Earning Swift.
Start now L
ReadString
ReadString needs a byte as a delimiter, read from the buffer to find the first occurrence of the delimiter (Delim), found, the beginning of the buffer from the head to the delimiter of all the byte to return, as a string, after returning, the buffer will also be empty part
Similar to the Readbytes

ReadString reads until the first occurrence of delim in the input,
Returning a string containing the data up to and including the delimiter.
If ReadString encounters an error before finding a delimiter,
It returns the data read before the error and the error itself (often IO. EOF).
ReadString returns ERR! = Nil if and only if the returned data does not end
In Delim.
Func (b *buffer) ReadString (Delim byte) (line string, err error) {}
Readfrom
Implement IO from one. Reader interface R, read the contents of R into the buffer, N returns the number of reads

Readfrom reads data from R until EOF and appends it to the buffer, growing
The buffer as needed. The return value n is the number of bytes read. Any
Error except IO. EOF encountered during the read is also returned. If the
Buffer becomes too large, readfrom'll panic with Errtoolarge.
Func (b *buffer) readfrom (R io. Reader) (n Int64, err error) {}
Func Readfrom () {
Test.txt content is "the future"
File, _: = OS. Open ("Learngo/bytes/text.txt")
BUF: = bytes. Newbufferstring ("Learning swift.")
Buf. Readfrom (file)//Append text.txt content to the end of the buffer
Fmt. Println (BUF. String ())
}
Print:

=======readfrom===
Learning Swift. Future
Reset
Empty data, no data to read

Reset resets the buffer so it has no content.
B.reset () is the same as B.truncate (0).
Func (b *buffer) Reset () {b.truncate (0)}
Func Reset () {
Bufs: = bytes. Newbufferstring ("Now start learning swift.")
Fmt. Println (Bufs. String ())

bufs.Reset()fmt.Println("::已经清空了bufs的缓冲内容::")fmt.Println(bufs.String())

}
Print:

=======reset======
Start learning Swift now.
:: The buffer content of Bufs has been emptied::
String
Returns unread data as a string

String returns the contents of the unread portion of the buffer
As a string. If The Buffer is a nil pointer, it returns "".
Func (b *buffer) string () string {}

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.