Go bytes Pack

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

Go bytes Pack

The use of the basic method of bytes Package

Package Mainimport ("bytes") func writeUInt16 (Buff []byte, data uint16) {for i: = 0; i < 2; i++ {buff[i] = byte (data ;> UINT (i*8))}}func spilt (R rune) bool {if r = = ' C ' {return True}return False}func main () {println ("Hello World") buff1 : = Make ([]byte, 2)//Create a slice writeUInt16 (buff1, UInt16 ()) Buff2: = Make ([]byte, 2)//Create a slice writeUInt16 (BUFF2, UInt16 (12) )//Compare two byte array slices res: = bytes. Compare (buff1, BUFF2) println (res)//String conversion to byte array buff3: = []byte ("Hello World Hello World") seq: = []byte ("Hello")//Count Co Unts the number of non-overlapping instances of sep in sres = bytes. Count (BUFF3, seq) println (res)//Contains reports whether Subslice is within bcontains: = bytes. Contains (BUFF3, seq)//trueprintln (Contains) res = bytes. Index (BUFF3, seq)//0PRINTLN (res) res = bytes. LastIndex (BUFF3, seq) println (res)/**rune literals is just an integer value (as you ve written). They is "mapped" to their Unicode codepoint. */a: = Rune (' e ') res = bytes. Indexrune (BUFF3, a)// -1println (RES) println ("------------") Buff5: = []byte (" ABCABCABCABC ")//SPLITN with Sep as a delimiter, the S is cut into multiple substrings, the result does not include Sep itself//if Sep is empty, then S is cut into Unicode word list characters// If there is no sep in S, then the entire s as [][]byte's first element returns//Parameter n indicates the maximum number of substrings to be cut out, the excess portion will no longer be sliced//if n is 0, then nil is returned, if n is less than 0, the number of slices is not limited, all slices arr: = by Tes. SPLITN (Buff5, []byte ("a"), 3) for _, V: = Range Arr {for _, T: = Range v {print (t) print (",")}println ("|")} fields are delimited by contiguous whitespace characters, and s are cut into substrings, and the result contains no whitespace characters themselves//whitespace characters: \ t, \ n, \v, \f, \ R, ', u+0085 (NEL), u+00a0 (NBSP)//If s contains only white space Character, an empty list is returned println ("------------") Buff6: = []byte ("ABC abc abc abc") arr = bytes. Fields (BUFF6) for _, V: = Range Arr {for _, T: = Range v {print (t) print (",")}println ("|")} Fieldsfunc is delimited by one or more successive characters that satisfy F (rune),//splits s into multiple substrings, the result does not contain the delimiter itself//if s does not meet the character of F (rune), an empty list println ("----------- -") Buff7: = []byte (" abcabcabcabc ") arr = bytes. Fieldsfunc (BUFF7, spilt) for _, V: = Range Arr {for _, T: = Range v {print (t) print (",")}println ("|")} BUFF8: = []byte ("I am Chinese")//will cut s into Unicode code point list data: = bytes. Runes (BUFF8) for _, Elem: = Range Data {println (string (elem))}//title modifies the first letter of all words in S to its Title format buff9: = bytes. Title (BUFF7) println (String (BUFF9))//Map replaces the character in s that satisfies mapping (rune) with the return value of mapping (rune)//If mapping (rune) returns a negative number, the corresponding character is Delete buff10: = bytes. Map (func (R rune) Rune {if r = = ' C ' {return ' a '}return R}, Buff7) println (String (BUFF10))}

Bytes Package Structure Body-bytes. Reader

Reader.go file

// A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker,// io.ByteScanner, and io.RuneScanner interfaces by reading from// a byte slice.// Unlike a Buffer, a Reader is read-only and supports seeking.type Reader struct {s        []bytei        int64 // current reading indexprevRune int   // index of previous rune; or < 0}

Reader implements the following interfaces,

io.Readerio.ReaderAt io.WriterTo io.Seekerio.ByteScannerio.RuneScanner

Unlike a Buffer, a Reader is read-only and supports seeking.

The method that the reader struct belongs to,

 func newreader (b []byte) *readerfunc (R *reader) Len () int//Read implements the IO. Reader interface//read reads len (b) bytes into B. Func (R *reader) Read (b []byte) (n int, err error)//ReadAt implements the IO. Readerat interface//From offset off starts reading Len (b) bytes to B in func (R *reader) ReadAt (b []byte, off Int64) (n int, err Error) func (R *rea der) ReadByte () (Byte, error) func (R *reader) readrune () (Ch rune, size int, err Error) func (R *reader) Reset (b []byte)// Seek implements the IO. Seeker Interface.func (R *reader) Seek (offset int64, whence int) (Int64, Error) func (R *reader) Size () int64//unreadbyte Implements the IO. Bytescanner Interfacefunc (R *reader) unreadbyte () error//Unreadrune implements the IO. Runescanner Interfacefunc (R *reader) Unreadrune () error//WriteTo implements the IO. WriteTo interface//WriteTo writes data to W until there ' s no more data to write or//when an error Occurs.func (R *reader ) WriteTo (w io. Writer) (n Int64, err error)  

Example of using the

method,

Package Mainimport ("bytes" "FMT" "IO") func main () {b1: = []byte ("Hello world!") Reader: = bytes. Newreader (B1)//Read method Buff: = Make ([]byte, 5) count, err: = Reader. Read (Buff) if err! = Nil {return}fmt. Printf ("Read count =%d,read data =%s\n", count, String (buff))//ReadAt method Buff2: = Make ([]byte, 5) count, err = reader. ReadAt (BUFF2, 6) if err! = Nil {return}fmt. Printf ("Read count =%d,read data =%s\n", Count, String (BUFF2)) for {///In turn returns the unread byte B, err: = Reader. ReadByte () If err = = Io. EOF {break}println (string (b))}println ("--------") b2: = []byte ("Hello World! ") Reader2: = bytes. Newreader (B2) for {//returns Runer, _, Err: = Reader2, which is not read in turn. Readrune () If err = = Io. EOF {break}println (string (R))}b3: = []byte ("String Builder")//Reset resets the Reader to is reading from B.reader2.reset ( B3) println (reader2. Len ()) println ("--------") Reader3: = bytes. Newreader (B1)//Seek sets the next Read or Write offset, which is interpreted depending on whence://0, relative to the beginning of the file, 1 for the current offset, and 2 for the opposite end. Seek returns a new offset and an error, if any. ABS, Err: = Reader3. Seek (-2, 2) println (ABS) b, _: = Reader3. ReadByte () println (string (b))}

Bytes Package Structure Body-bytes. Buffer

Buffer.go file,

// 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 call to WriteRunebootstrap [64]byte          // memory to hold first slice; helps small buffers avoid allocation.lastRead  readOp            // last read operation, so that Unread* can work correctly.}

The method that the buffer struct belongs to,

Func Newbuffer (buf []byte) *bufferfunc newbufferstring (S string) *bufferfunc (b *buffer) Bytes () []bytefunc (b *buffer) Ca P () IntFunc (b *buffer) Grow (n int) func (b *buffer) Len () IntFunc (b *buffer) Next (n int) []bytefunc (b *buffer) Read (p [] BYTE) (n int, err error) func (b *buffer) ReadByte () (Byte, error) func (b *buffer) readbytes (Delim byte) (line []byte, err Error) func (b *buffer) readfrom (R io. Reader) (n Int64, err error) func (b *buffer) Readrune () (R rune, size int, err error) func (b *buffer) ReadString (Delim byt  e) (line string, err Error) func (b *buffer) Reset () func (b *buffer) string () Stringfunc (b *buffer) Truncate (n int) func (b *buffer) Unreadbyte () Errorfunc (b *buffer) Unreadrune () Errorfunc (b *buffer) Write (P []byte) (n int, err error) func (b *buffer) WriteByte (c byte) Errorfunc (b *buffer) Writerune (R rune) (n int, err error) func (b *buffer) writestring (s string ) (n int, err error) func (b *buffer) writeto (w io). Writer) (n Int64, err error)

Example of how to use the

Package Mainimport ("bytes" "FMT") func main () {b1: = []byte ("Hello world!") BUF: = bytes. Newbuffer (B1) fmt. Printf ("Buff len=%d\n", buf. Len ()) fmt. Printf ("Buff cap=%d\n", buf. Cap ()) buf. Grow (+) fmt. Printf ("Buff len=%d\n", buf. Len ()) fmt. Printf ("Buff cap=%d\n", buf. Cap ()) B2: = Make ([]byte, 6)//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 had no data to return, and err is IO. EOF (unless Len (p) is zero); Otherwise it is Nil.buf.Read (B2) println (String (b2))//hellob3: = buf. Next (5) println (String (b3))//WORLDB4: = buf. Next (3) println (String (B4)) Buf2: = bytes. Newbuffer (B1)//Readbytes reads until the first occurrence of Delim in the input,//returning a slice containing the data Up to and including the delimiter.b5, _: = Buf2. Readbytes (Byte (")) println (Len (B5)) println (String (B5)) B6: = []byte (" Go Programming ") buf3: = bytes. Newbuffer (B1)//Write appends the contents of p to the buffer, growing the bufferas//Needed.buf3.Write (B6) println (String (buf3. Bytes ()))}

=======end=======

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.