Golang标准库之bytes介绍

本次主要介绍golang中的标准库bytes,基本上参考了 字节 | bytesGolang标准库——bytes 文章。

bytes库主要包含 5 大部分,即:

  • 常量
  • 变量
  • 函数
  • Buffer
  • Reader

我们依次学习上面的 5 大部分。

1、常量

const MinRead = 512

bytes.MinRead 是一个常量,表示在使用 ReadFrom 方法从 io.Reader 中读取数据时,每次读取的最小字节数。如果 io.Reader 的 Read 方法返回的字节数小于 bytes.MinRead,ReadFrom 方法会尝试再次读取,直到读取的字节数达到 bytes.MinRead 或者 io.EOF。这个常量的值为 512。

对上面解释不太清楚的同学,可以去看看源码,然后再看一看 func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) 这个方法就能够理解了。

2、变量

// ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer.
var ErrTooLarge = errors.New("bytes.Buffer: too large")

bytes.ErrTooLarge 是 Go 语言标准库中 bytes 包的一个错误变量,表示在执行某些操作时,输入的数据过大,超出了 bytes 包所能处理的范围。

具体来说,当使用 bytes.Buffer 类型的 Write 方法写入数据时,如果写入的数据长度超过了缓冲区的容量,就会返回 bytes.ErrTooLarge 错误。类似地,当使用 bytes.Reader 类型的 Read 方法读取数据时,如果要读取的数据长度超过了缓冲区的长度,也会返回 bytes.ErrTooLarge 错误。

bytes.ErrTooLarge 的作用是提醒开发者注意输入数据的大小,避免因为数据过大而导致程序崩溃或者出现其他问题。

3、函数

3.1 func Compare

函数定义:

func Compare(a, b []byte) int

Compare函数返回一个整数表示两个[]byte切片按字典序比较的结果。如果a==b返回0;如果a<b返回-1;否则返回+1。nil参数视为空切片。

func main() {
 fmt.Println(bytes.Compare([]byte{},[]byte{})) // 0
 fmt.Println(bytes.Compare([]byte{1},[]byte{2})) // -1
 fmt.Println(bytes.Compare([]byte{2},[]byte{1})) // 1
 fmt.Println(bytes.Compare([]byte{},nil)) //0
 fmt.Println([]byte{} == nil) // false
}

3.2 func Equal

函数定义:

func Equal(a, b []byte) bool

判断两个切片的内容是否完全相同。 注意:nil 参数视为空切片。

func main() {
 fmt.Println(bytes.Equal([]byte{},[]byte{})) // true
 fmt.Println(bytes.Equal([]byte{'A', 'B'},[]byte{'a'})) // false
 fmt.Println(bytes.Equal([]byte{'a'},[]byte{'a'})) // true
 fmt.Println(bytes.Equal([]byte{},nil)) // true
 fmt.Println([]byte{} == nil) // false
}

3.3 func EqualFold

函数定义:

func EqualFold(s, t []byte) bool

判断两个UTF-8编码的字符串s和t是否在Unicode的折叠大小写规则下相等,这种规则比简单的大小写不敏感更加通用。也就是说,EqualFold函数会将两个字符串中的字符先转换为相同的大小写形式,再进行比较,从而判断它们是否相等。

func main() {
 fmt.Println(bytes.EqualFold([]byte{},[]byte{})) // true
 fmt.Println(bytes.EqualFold([]byte{'A'},[]byte{'a'})) // true
 fmt.Println(bytes.EqualFold([]byte{'B'},[]byte{'a'})) // false
 fmt.Println(bytes.EqualFold([]byte{},nil)) // true
}

3.4 func Runes

函数定义:

func Runes(s []byte) []rune

Runes函数返回和s等价的[]rune切片。(将utf-8编码的unicode码值分别写入单个rune)

func main() {
 fmt.Println([]byte("你好world")) // [228 189 160 229 165 189 119 111 114 108 100]
 fmt.Println(bytes.Runes([]byte("你好world"))) // [20320 22909 119 111 114 108 100]
 fmt.Println([]rune("你好world")) // [20320 22909 119 111 114 108 100] 
}

3.5 func HasPrefix

函数定义:

func HasPrefix(s, prefix []byte) bool

判断s是否有前缀切片prefix。

3.6 func HasSuffix

函数定义:

func HasSuffix(s, suffix []byte) bool

判断s是否有后缀切片suffix。

3.7 func Contains

函数定义:

func Contains(b, subslice []byte) bool

判断切片b是否包含子切片subslice。

3.8 func Count

函数定义:

func Count(s, sep []byte) int

Count计算s中有多少个不重叠的sep子切片。

3.9 func Index

函数定义:

func Index(s, sep []byte) int

子切片sep在s中第一次出现的位置,不存在则返回-1。

3.10 func IndexByte

函数定义:

func IndexByte(s []byte, c byte) int

字符c在s中第一次出现的位置,不存在则返回-1。

3.11 func ndexRune

函数定义:

func IndexRune(s []byte, r rune) int

unicode字符r的utf-8编码在s中第一次出现的位置,不存在则返回-1。

3.12 func IndexAny

函数定义:

func IndexAny(s []byte, chars string) int

字符串chars中的任一utf-8编码在s中第一次出现的位置,如不存在或者chars为空字符串则返回-1

package main
import (
	"bytes"
	"fmt"
)
func main() {
	fmt.Println(bytes.IndexAny([]byte("chicken"), "aeiouy")) // 2
	fmt.Println(bytes.IndexAny([]byte("crwth"), "aeiouy")) // -1
}

3.13 func IndexFunc

函数定义:

func IndexFunc(s []byte, f func(r rune) bool) int

IndexFunc 将 s 解释为一系列UTF-8编码的Unicode代码点。它返回满足 f(c) 的第一个 Unicode 代码点的 s 中的字节索引,否则返回 -1。

package main
import (
	"bytes"
	"fmt"
	"unicode"
)
func main() {
	f := func(c rune) bool {
 // unicode.Han 代表的是 unicode 中汉字的字符集
	return unicode.Is(unicode.Han, c)
	}
	fmt.Println(bytes.IndexFunc([]byte("Hello, 世界"), f)) // 7
	fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f)) // -1
}

3.14 func LastIndex

函数定义:

func LastIndex(s, sep []byte) int

切片sep在字符串s中最后一次出现的位置,不存在则返回-1。

3.15 func LastIndexAny

func LastIndexAny(s []byte, chars string) int

字符串chars中的任一utf-8字符在s中最后一次出现的位置,如不存在或者chars为空字符串则返回-1。

3.16 func LastIndexFunc

func LastIndexFunc(s []byte, f func(r rune) bool) int

s中最后一个满足函数f的unicode码值的位置i,不存在则返回-1。

func main() {
 fmt.Println(bytes.HasPrefix([]byte{1, 2, 3}, []byte{1})) // true
 fmt.Println(bytes.HasPrefix([]byte{1, 2, 3}, []byte{2})) // false
 fmt.Println(bytes.HasSuffix([]byte{1, 2, 3, 3}, []byte{3, 3})) // true
 fmt.Println(bytes.HasSuffix([]byte{1, 2, 3, 3}, []byte{3, 4})) // false
 fmt.Println(bytes.Contains([]byte{1, 2, 3}, []byte{1})) // true
 fmt.Println(bytes.Contains([]byte{1, 2, 3}, []byte{1, 3})) // false
 fmt.Println(bytes.Index([]byte{1, 2, 3, 4, 5}, []byte{4, 5})) // 3
 fmt.Println(bytes.Index([]byte{1, 2, 3, 4, 5}, []byte{0, 1})) // -1
 fmt.Println(bytes.IndexByte([]byte{1, 2, 3}, 3)) // 2
 fmt.Println(bytes.IndexByte([]byte{1, 2, 3}, 0)) // -1
 fmt.Println(bytes.LastIndex([]byte("hi go"), []byte("go"))) // 3
 fmt.Println(bytes.LastIndex([]byte{1, 2, 3}, []byte{2, 3})) // 1
 fmt.Println(bytes.IndexAny([]byte("hi go"), "go")) // 3
 fmt.Println(bytes.Count([]byte("hi go go go go go go go go go"), []byte("go"))) // 9
 fmt.Println(bytes.IndexRune([]byte("你好吗,不太好啊,hi go go go go go go go go go"), '不')) // 9
 fmt.Println(bytes.IndexFunc([]byte("hi go"), func(r rune) bool {
 return r == 'g'
 })) // 3
}

3.17 func Title

func Title(s []byte) []byte

返回s中每个单词的首字母都改为标题格式的拷贝。

BUG: Title用于划分单词的规则不能很好的处理Unicode标点符号。

fmt.Printf("%s\n", bytes.Title([]byte("her royal highness"))) // Her Royal Highness
fmt.Printf("%s\n", bytes.Title([]byte("hEr royal highness"))) // HEr Royal Highness

3.18 func ToLower

func ToLower(s []byte) []byte

返回将所有字母都转为对应的小写版本的拷贝。

fmt.Printf("%s", bytes.ToLower([]byte("Gopher"))) // gopher

3.19 func ToLowerSpecial

func ToLowerSpecial(_case unicode.SpecialCase, s []byte) []byte

ToLowerSpecial 将 s 视为 UTF-8 编码的字节并返回一个副本,其中所有 Unicode 字母都映射到它们的小写,优先考虑特殊的大小写规则。

package main
import (
 "bytes"
 "fmt"
 "unicode"
)
func main() {
 str := []byte("AHOJ VÝVOJÁRİ GOLANG")
 totitle := bytes.ToLowerSpecial(unicode.AzeriCase, str)
 fmt.Println("Original : " + string(str))
 fmt.Println("ToLower : " + string(totitle))
}

结果:

Original : AHOJ VÝVOJÁRİ GOLANG
ToLower : ahoj vývojári golang

3.20 func ToUpper

func ToUpper(s []byte) []byte

返回将所有字母都转为对应的大写版本的拷贝。

3.21 func ToUpperSpecial

func ToUpperSpecial(_case unicode.SpecialCase, s []byte) []byte

使用_case规定的字符映射,返回将所有字母都转为对应的大写版本的拷贝。

3.22 func ToTitle

func ToTitle(s []byte) []byte

返回将所有字母都转为对应的标题版本的拷贝。

3.23 func ToTitleSpecial

func ToTitleSpecial(_case unicode.SpecialCase, s []byte) []byte

使用_case规定的字符映射,返回将所有字母都转为对应的标题版本的拷贝。

func main() {
 fmt.Println(string(bytes.Title([]byte("AAA")))) // AAA
 fmt.Println(string(bytes.Title([]byte("aaa")))) // Aaa
 fmt.Println(string(bytes.ToTitle([]byte("Aaa")))) // AAA
 fmt.Println(string(bytes.ToUpper([]byte("Aaa")))) // AAA
 fmt.Println(string(bytes.ToUpperSpecial(unicode.SpecialCase{}, []byte("Aaa")))) // AAA
 fmt.Println(string(bytes.ToLower([]byte("aAA")))) // aaa
 fmt.Println(string(bytes.ToLowerSpecial(unicode.SpecialCase{}, []byte("aAA")))) // aaa
}

3.24 func Repeat

func Repeat(b []byte, count int) []byte

返回count个b串联形成的新的切片。

3.25 func Replace

func Replace(s, old, new []byte, n int) []byte

返回将 s 中 前n个 不重叠 old切片序列 都替换为 new 的新的切片拷贝,如果n<0会替换所有old子切片。

package main
import (
	"bytes"
	"fmt"
)
func main() {
	fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("k"), []byte("ky"), 2))
	fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("oink"), []byte("moo"), -1))
}

结果:

oinky oinky oink
moo moo moo

3.26 func Map

func Map(mapping func(r rune) rune, s []byte) []byte

Map 根据映射函数返回字节切片s的所有字符修改后的副本。如果映射返回负值,则字符将从字符串中删除而不会被替换。 s 和输出中的字符被解释为 UTF-8 编码的 Unicode 代码点。

package main
import (
	"bytes"
	"fmt"
)
func main() {
	rot13 := func(r rune) rune {
	switch {
	case r >= 'A' && r <= 'Z':
	return 'A' + ('A'+13)%26
	case r >= 'a' && r <= 'z':
	return 'a' + ('a'+13)%26
	}
	return r
	}
	fmt.Printf("%s", bytes.Map(rot13, []byte("'Twas brillig and the slithy gopher...")))
}
// 输出
'Gjnf oevyyvt naq gur fyvgul tbcure...

3.27 func Trim

func Trim(s []byte, cutset string) []byte

返回将s前后端所有cutset包含的unicode码值都去掉的子切片。(共用底层数组)

3.28 func TrimSpace

func TrimSpace(s []byte) []byte

返回将s前后端所有空白(unicode.IsSpace指定)都去掉的子切片。(共用底层数组)

3.29 func TrimFunc

func TrimFunc(s []byte, f func(r rune) bool) []byte

返回将s前后端所有满足f的unicode码值都去掉的子切片。(共用底层数组)

3.30 func TrimLeft

func TrimLeft(s []byte, cutset string) []byte

返回将s前端所有cutset包含的unicode码值都去掉的子切片。(共用底层数组)

3.31 func TrimLeftFunc

func TrimLeftFunc(s []byte, f func(r rune) bool) []byte

返回将s前端所有满足f的unicode码值都去掉的子切片。(共用底层数组)

3.32 func TrimPrefix

func TrimPrefix(s, prefix []byte) []byte

返回去除s可能的前缀prefix的子切片。(共用底层数组)

3.33 func TrimRight

func TrimRight(s []byte, cutset string) []byte

返回将s后端所有cutset包含的unicode码值都去掉的子切片。(共用底层数组)

3.34 func TrimRightFunc

func TrimRightFunc(s []byte, f func(r rune) bool) []byte

返回将s后端所有满足f的unicode码值都去掉的子切片。(共用底层数组)

3.35 func TrimSuffix

func TrimSuffix(s, suffix []byte) []byte

返回去除s可能的后缀suffix的子切片。(共用底层数组)

func main() {
 fmt.Println(bytes.Repeat([]byte{1,2},3)) // [1 2 1 2 1 2]
 fmt.Println(bytes.Replace([]byte{1,2,1,2,3,1,2,1,2}, []byte{1,2}, []byte{0,0},3)) // [0 0 0 0 3 0 0 1 2]
 fmt.Println(string(bytes.Map(func(r rune) rune {
 return r + 1 // 将每一个字符都+1
 },[]byte("abc")))) // bcd
 fmt.Println(string(bytes.Trim([]byte("hello my"), "my"))) // hello 
 fmt.Println(string(bytes.TrimSpace([]byte(" hello my bro ")))) // hello my bro
 fmt.Println(string(bytes.TrimLeft([]byte("hi hi go"), "hi"))) // hi go
 fmt.Println(string(bytes.TrimPrefix([]byte("hi hi go"),[]byte("hi")))) // hi go
 fmt.Println(string(bytes.TrimSuffix([]byte("hi go go"),[]byte("go")))) // hi go
}

3.36 func Fields

func Fields(s []byte) [][]byte

返回将字符串按照空白(unicode.IsSpace确定,可以是一到多个连续的空白字符)分割的多个子切片。如果字符串全部是空白或者是空字符串的话,会返回空切片。

3.37 func FieldsFunc

func FieldsFunc(s []byte, f func(rune) bool) [][]byte

类似Fields,但使用函数f来确定分割符(满足f的utf-8码值)。如果字符串全部是分隔符或者是空字符串的话,会返回空切片。

3.38 func Split

func Split(s, sep []byte) [][]byte

用去掉s中出现的sep的方式进行分割,会分割到结尾,并返回生成的所有[]byte切片组成的切片(每一个sep都会进行一次切割,即使两个sep相邻,也会进行两次切割)。如果sep为空字符,Split会将s切分成每一个unicode码值一个[]byte切片。

3.39 func SplitN

func SplitN(s, sep []byte, n int) [][]byte

用去掉s中出现的sep的方式进行分割,会分割到最多n个子切片,并返回生成的所有[]byte切片组成的切片(每一个sep都会进行一次切割,即使两个sep相邻,也会进行两次切割)。如果sep为空字符,Split会将s切分成每一个unicode码值一个[]byte切片。参数n决定返回的切片的数目:

n > 0 : 返回的切片最多n个子字符串;最后一个子字符串包含未进行切割的部分。
n == 0: 返回nil
n < 0 : 返回所有的子字符串组成的切片

3.40 func SplitAfter

func SplitAfter(s, sep []byte) [][]byte

用从s中出现的sep后面切断的方式进行分割,会分割到结尾,并返回生成的所有[]byte切片组成的切片(每一个sep都会进行一次切割,即使两个sep相邻,也会进行两次切割)。如果sep为空字符,Split会将s切分成每一个unicode码值一个[]byte切片。

3.41 func SplitAfterN

func SplitAfterN(s, sep []byte, n int) [][]byte

用从s中出现的sep后面切断的方式进行分割,会分割到最多n个子切片,并返回生成的所有[]byte切片组成的切片(每一个sep都会进行一次切割,即使两个sep相邻,也会进行两次切割)。如果sep为空字符,Split会将s切分成每一个unicode码值一个[]byte切片。参数n决定返回的切片的数目:

n > 0 : 返回的切片最多n个子字符串;最后一个子字符串包含未进行切割的部分。
n == 0: 返回nil
n < 0 : 返回所有的子字符串组成的切片

3.42 func Join

func Join(s [][]byte, sep []byte) []byte

将一系列[]byte切片连接为一个[]byte切片,之间用sep来分隔,返回生成的新切片。

func main() {
 s := bytes.Fields([]byte(" hi 你啊, is not good, my boy"))
 for _,v := range s {
 fmt.Print(string(v) + "|")// hi|你啊,|is|not|good,|my|boy|
 }
 fmt.Println()
 s = bytes.FieldsFunc([]byte(" hi 你啊, is-not.good, my,boy"),func(r rune) bool {
 return r == ','||r == '-'||r == '.' // 只要是,-. 都可以作为分隔符
 })
 for _,v := range s {
 fmt.Print(string(v)+"|")// hi 你啊| is|not|good| my|boy|
 }
 fmt.Println()
 s = bytes.Split([]byte(" hi 你啊, is not good, is my boy"),[]byte("is"))
 for _,v := range s {
 fmt.Print(string(v) + "|")// | hi 你啊, | not good, | my boy|
 }
 fmt.Println()
 fmt.Println(bytes.Join([][]byte{{1,1},{2,2},{3,3}},[]byte{9})) // [1 1 9 2 2 9 3 3]
}

4、type Reader

type Reader struct {
 s []byte // 存储数据的byte切片
 i int64 // current reading index => 当前读到的位置
 prevRune int // index of previous rune; or < 0 => 前一个rune的索引
}

Reader类型通过从一个[]byte读取数据,实现了io.Reader、io.Seeker、io.ReaderAt、io.WriterTo、io.ByteScanner、io.RuneScanner接口。

4.1 func NewReader

func NewReader(b []byte) *Reader

NewReader创建一个从b读取数据的Reader。

4.2 func (*Reader) Len

func (r *Reader) Len() int

Len返回r包含的切片中还没有被读取的部分。

4.3 func (*Reader) Read

func (r *Reader) Read(b []byte) (n int, err error)

从 r 中读取字节到 b 中

package main
import (
	"bytes"
	"fmt"
)
func main() {
	r := bytes.NewBufferString("hello world")
	fmt.Printf("r.Len() -> %d\n", r.Len())
	m := make([]byte, 5)
	r.Read(m)
	fmt.Printf("r.Len() -> %d\n", r.Len())
	fmt.Printf("%s\n", m)
}
// 结果
r.Len() -> 11
r.Len() -> 6
hello

4.4 func (*Reader) ReadByte

func (r *Reader) ReadByte() (b byte, err error)

读取一个字节

package main
import (
	"bytes"
	"fmt"
)
func main() {
	r := bytes.NewBufferString("hello world")
	fmt.Printf("%v\n", r.Bytes())
	fmt.Printf("r.Len() -> %d\n", r.Len())
	//m := make([]byte, 5)
	a, err := r.ReadByte()
	fmt.Printf("r.Len() -> %d\n", r.Len())
	fmt.Printf("%v \n", a)
	fmt.Println(err)
}
// 结果
[104 101 108 108 111 32 119 111 114 108 100]
r.Len() -> 11
r.Len() -> 10
104 
<nil>

4.5 func (*Reader) UnreadByte

func (r *Reader) UnreadByte() error

4.6 func (*Reader) ReadRune

func (r *Reader) ReadRune() (ch rune, size int, err error)

4.7 func (*Reader) UnreadRune

func (r *Reader) UnreadRune() error

如果上一个操作不是 ReadRune ,将报错。

如果是,将 ReadRune 读取的影响复位。这里执行下看看结果就明白意思了。

package main
import (
	"bytes"
	"fmt"
)
func main() {
	r := bytes.NewBufferString("hello world")
	fmt.Printf("%v\n", r.Bytes())
	fmt.Printf("r.Len() -> %d\n", r.Len())
	
	s, b, err := r.ReadRune()
	fmt.Println(s, b, err)
	//err = r.UnreadRune()
	fmt.Println(err)
	fmt.Println(r.Bytes())
}

4.8 func (*Reader) Seek

func (r *Reader) Seek(offset int64, whence int) (int64, error)

Seek实现了io.Seeker接口。

package main
import (
	"fmt"
	"strings"
)
func main() {
	reader := strings.NewReader("Go语言学习园地")
	reader.Seek(2, 0)
	r, _, _ := reader.ReadRune()
	fmt.Printf("%c\n", r)
}
// 结果
语

4.9 func (*Reader) ReadAt

func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)

4.10 func (*Reader) WriteTo

func (r *Reader) WriteTo(w io.Writer) (n int64, err error)

WriteTo实现了io.WriterTo接口。

func main() {
 r := bytes.NewReader([]byte("ABCDEFGHIJKLMN IIIIII LLLLLLLL SSSSSS"))
 fmt.Println(r.Len()) // 37
 fmt.Println(r.Size()) // 37
 tmp := make([]byte,5)
 n,_ := r.Read(tmp)
 fmt.Println(string(tmp[:n])) // ABCDE
 fmt.Println(r.Len(),r.Size()) // 32 37
 fmt.Println(r.ReadByte()) // 70 <nil> // F
 fmt.Println(r.ReadRune()) // 71 1 <nil>
 fmt.Println(r.Len(),r.Size()) // 30 37
 b := []byte("III") // cap 3
 n,_ = r.ReadAt(b,1) 
 fmt.Println(string(b),n) // BCD 3
 r.Reset([]byte("Hi,My god"))
 fmt.Println(r.Len(),r.Size()) // 9 9
 r.WriteTo(os.Stdout) // Hi,My god
}

5、type Buffer

type Buffer struct {
 buf []byte // contents are the bytes buf[off : len(buf)] => buffer的数据
 off int // read at &buf[off], write at &buf[len(buf)] => buffer的目前读取到的位置
 lastRead readOp // last read operation, so that Unread* can work correctly. => 最后一次的读取操作
}

Buffer是一个实现了读写方法的可变大小的字节缓冲。本类型的零值是一个空的可用于读写的缓冲。

5.1 func NewBuffer

func NewBuffer(buf []byte) *Buffer

NewBuffer使用buf作为初始内容创建并初始化一个Buffer。本函数用于创建一个用于读取已存在数据的buffer;也用于指定用于写入的内部缓冲的大小,此时,buf应为一个具有指定容量但长度为0的切片。buf会被作为返回值的底层缓冲切片。

大多数情况下,new(Buffer)(或只是声明一个Buffer类型变量)就足以初始化一个Buffer了。

5.2 func NewBufferString

func NewBufferString(s string) *Buffer

NewBuffer使用s作为初始内容创建并初始化一个Buffer。本函数用于创建一个用于读取已存在数据的buffer。

大多数情况下,new(Buffer)(或只是声明一个Buffer类型变量)就足以初始化一个Buffer了。

第一种方式
buffer := new(bytes.Buffer) // 使用new函数
第二种方式
buffer := bytes.NewBuffer([]byte{}) // 使用bytes包的NewBuffer函数
第三种方式
buffer := bytes.NewBufferString("") // 使用bytes包的NewBufferString函数

5.3 func (*Buffer) Len

func (b *Buffer) Len() int

返回缓冲中未读取部分的字节长度;b.Len() == len(b.Bytes())。

5.4 func (*Buffer) Bytes

func (b *Buffer) Bytes() []byte

返回未读取部分字节数据的切片,len(b.Bytes()) == b.Len()。如果中间没有调用其他方法,修改返回的切片的内容会直接改变Buffer的内容。

5.5 func (*Buffer) String

func (b *Buffer) String() string

将未读取部分的字节数据作为字符串返回,如果b是nil指针,会返回空字符串。

5.6 func (*Buffer) Grow

func (b *Buffer) Grow(n int)

必要时会增加缓冲的容量,以保证n字节的剩余空间。调用Grow(n)后至少可以向缓冲中写入n字节数据而无需申请内存。如果n小于零或者不能增加容量都会panic。

5.7 func (*Buffer) Read

func (b *Buffer) Read(p []byte) (n int, err error)

Read方法从缓冲中读取数据直到缓冲中没有数据或者读取了len(p)字节数据,将读取的数据写入p。返回值n是读取的字节数,除非缓冲中完全没有数据可以读取并写入p,此时返回值err为io.EOF;否则err总是nil。

5.8 func (*Buffer) Next

func (b *Buffer) Next(n int) []byte

返回未读取部分前n字节数据的切片,并且移动读取位置,就像调用了Read方法一样。如果缓冲内数据不足,会返回整个数据的切片。切片只在下一次调用b的读/写方法前才合法。

5.9 func (*Buffer) ReadByte

func (b *Buffer) ReadByte() (c byte, err error)

ReadByte读取并返回缓冲中的下一个字节。如果没有数据可用,返回值err为io.EOF。

5.10 func (*Buffer) UnreadByte

func (b *Buffer) UnreadByte() error

UnreadByte吐出最近一次读取操作读取的最后一个字节。如果最后一次读取操作之后进行了写入,本方法会返回错误。

5.11 func (*Buffer) ReadRune

func (b *Buffer) ReadRune() (r rune, size int, err error)

ReadRune读取并返回缓冲中的下一个utf-8码值。如果没有数据可用,返回值err为io.EOF。如果缓冲中的数据是错误的utf-8编码,本方法会吃掉一字节并返回(U+FFFD, 1, nil)。

5.12 func (*Buffer) UnreadRune

func (b *Buffer) UnreadRune() error

UnreadRune吐出最近一次调用ReadRune方法读取的unicode码值。如果最近一次读写操作不是ReadRune,本方法会返回错误。(这里就能看出来UnreadRune比UnreadByte严格多了)

5.13 func (*Buffer) ReadBytes

func (b *Buffer) ReadBytes(delim byte) (line []byte, err error)

ReadBytes读取直到第一次遇到delim字节,返回一个包含已读取的数据和delim字节的切片。如果ReadBytes方法在读取到delim之前遇到了错误,它会返回在错误之前读取的数据以及该错误(一般是io.EOF)。当且仅当ReadBytes方法返回的切片不以delim结尾时,会返回一个非nil的错误。

5.14 func (*Buffer) ReadString

func (b *Buffer) ReadString(delim byte) (line string, err error)

ReadString读取直到第一次遇到delim字节,返回一个包含已读取的数据和delim字节的字符串。如果ReadString方法在读取到delim之前遇到了错误,它会返回在错误之前读取的数据以及该错误(一般是io.EOF)。当且仅当ReadString方法返回的切片不以delim结尾时,会返回一个非nil的错误。

func main() {
 b := bytes.NewBufferString("ABCDEFGH")
 fmt.Println(b.String()) // ABCDEFGH
 fmt.Println(b.Len()) // 8
 fmt.Println(string(b.Next(2))) // AB
 tmp := make([]byte,2)
 n,_ := b.Read(tmp)
 fmt.Println(string(tmp[:n])) //CD
 nextByte,_ := b.ReadByte()
 fmt.Println(string(nextByte)) // E
 line,_ := b.ReadString('G')
 fmt.Println(line) // FG
 fmt.Println(b.String()) // H
 b = bytes.NewBufferString("abcdefgh")
 line2,_ := b.ReadBytes('b')
 fmt.Println(string(line2)) // ab
 fmt.Println(b.String()) // cdefgh
 r,n,_ := b.ReadRune()
 fmt.Println(r,n) // 99 1
 fmt.Println(string(b.Bytes())) // defgh
}

5.15 func (*Buffer) Write

func (b *Buffer) Write(p []byte) (n int, err error)

Write将p的内容写入缓冲中,如必要会增加缓冲容量。返回值n为len(p),err总是nil。如果缓冲变得太大,Write会采用错误值ErrTooLarge引发panic。

5.16 func (*Buffer) WriteString

func (b *Buffer) WriteString(s string) (n int, err error)

Write将s的内容写入缓冲中,如必要会增加缓冲容量。返回值n为len(p),err总是nil。如果缓冲变得太大,Write会采用错误值ErrTooLarge引发panic。

5.17 func (*Buffer) WriteByte

func (b *Buffer) WriteByte(c byte) error

WriteByte将字节c写入缓冲中,如必要会增加缓冲容量。返回值总是nil,但仍保留以匹配bufio.Writer的WriteByte方法。如果缓冲太大,WriteByte会采用错误值ErrTooLarge引发panic。

5.18 func (*Buffer) WriteRune

func (b *Buffer) WriteRune(r rune) (n int, err error)

WriteByte将unicode码值r的utf-8编码写入缓冲中,如必要会增加缓冲容量。返回值总是nil,但仍保留以匹配bufio.Writer的WriteRune方法。如果缓冲太大,WriteRune会采用错误值ErrTooLarge引发panic。

5.19 func (*Buffer) ReadFrom

func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom从r中读取数据直到结束并将读取的数据写入缓冲中,如必要会增加缓冲容量。返回值n为从r读取并写入b的字节数;会返回读取时遇到的除了io.EOF之外的错误。如果缓冲太大,ReadFrom会采用错误值ErrTooLarge引发panic。

5.20 func (*Buffer) WriteTo

func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)

WriteTo从缓冲中读取数据直到缓冲内没有数据或遇到错误,并将这些数据写入w。返回值n为从b读取并写入w的字节数;返回值总是可以无溢出的写入int类型,但为了匹配io.WriterTo接口设为int64类型。从b读取是遇到的非io.EOF错误及写入w时遇到的错误都会终止本方法并返回该错误。

5.21 func (*Buffer) Truncate

func (b *Buffer) Truncate(n int)

丢弃缓冲中除前n字节数据外的其它数据,如果n小于零或者大于缓冲容量将panic。

5.22 func (*Buffer) Reset

func (b *Buffer) Reset()

Reset重设缓冲,因此会丢弃全部内容,等价于b.Truncate(0)

func main() {
 b := new(bytes.Buffer)
 b.WriteByte('a')
 fmt.Println(b.String()) // a
 b.Write([]byte{98,99})
 fmt.Println(b.String()) // abc
 b.WriteString(" hello")
 fmt.Println(b.String()) // abc hello
 b.Truncate(3)
 fmt.Println(b.String()) // abc
 
 n,_ := b.WriteTo(os.Stdout) // abc
 fmt.Println(n) // 3
 b.Reset()
 fmt.Println(b.Len(),b.String()) // 0
}
作者:画个一样的我原文地址:https://www.cnblogs.com/huageyiyangdewo/p/17453457.html

%s 个评论

要回复文章请先登录注册