本次主要介紹golang中的標(biāo)準(zhǔn)庫bytes
,基本上參考了 字節(jié) | bytes 、Golang標(biāo)準(zhǔn)庫——bytes 文章。
bytes
庫主要包含 5 大部分,即:
- 常量
- 變量
- 函數(shù)
- Buffer
- Reader
我們依次學(xué)習(xí)上面的 5 大部分。
1、常量
const MinRead = 512
bytes.MinRead 是一個(gè)常量,表示在使用 ReadFrom 方法從 io.Reader 中讀取數(shù)據(jù)時(shí),每次讀取的最小字節(jié)數(shù)。如果 io.Reader 的 Read 方法返回的字節(jié)數(shù)小于 bytes.MinRead,ReadFrom 方法會(huì)嘗試再次讀取,直到讀取的字節(jié)數(shù)達(dá)到 bytes.MinRead 或者 io.EOF。這個(gè)常量的值為 512。
對(duì)上面解釋不太清楚的同學(xué),可以去看看源碼,然后再看一看
func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)
這個(gè)方法就能夠理解了。
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 語言標(biāo)準(zhǔn)庫中 bytes 包的一個(gè)錯(cuò)誤變量,表示在執(zhí)行某些操作時(shí),輸入的數(shù)據(jù)過大,超出了 bytes 包所能處理的范圍。
具體來說,當(dāng)使用 bytes.Buffer 類型的 Write 方法寫入數(shù)據(jù)時(shí),如果寫入的數(shù)據(jù)長度超過了緩沖區(qū)的容量,就會(huì)返回 bytes.ErrTooLarge 錯(cuò)誤。類似地,當(dāng)使用 bytes.Reader 類型的 Read 方法讀取數(shù)據(jù)時(shí),如果要讀取的數(shù)據(jù)長度超過了緩沖區(qū)的長度,也會(huì)返回 bytes.ErrTooLarge 錯(cuò)誤。
bytes.ErrTooLarge 的作用是提醒開發(fā)者注意輸入數(shù)據(jù)的大小,避免因?yàn)閿?shù)據(jù)過大而導(dǎo)致程序崩潰或者出現(xiàn)其他問題。
3、函數(shù)
3.1 func Compare
函數(shù)定義:
func Compare(a, b []byte) int
Compare函數(shù)返回一個(gè)整數(shù)表示兩個(gè)[]byte切片
按字典序
比較的結(jié)果。如果a==b返回0;如果a<b返回-1;否則返回+1。nil參數(shù)視為空切片。
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
函數(shù)定義:
func Equal(a, b []byte) bool
判斷兩個(gè)切片的內(nèi)容是否完全相同。
注意:nil 參數(shù)視為空切片。
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
函數(shù)定義:
func EqualFold(s, t []byte) bool
判斷兩個(gè)UTF-8編碼的字符串s和t是否在Unicode的折疊大小寫規(guī)則下相等,這種規(guī)則比簡單的大小寫不敏感更加通用。也就是說,EqualFold函數(shù)會(huì)將兩個(gè)字符串中的字符先轉(zhuǎn)換為相同的大小寫形式,再進(jìn)行比較,從而判斷它們是否相等。
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
函數(shù)定義:
func Runes(s []byte) []rune
Runes函數(shù)返回和s等價(jià)的[]rune切片。(將utf-8編碼的unicode碼值分別寫入單個(gè)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
函數(shù)定義:
func HasPrefix(s, prefix []byte) bool
判斷s是否有前綴切片prefix。
3.6 func HasSuffix
函數(shù)定義:
func HasSuffix(s, suffix []byte) bool
判斷s是否有后綴切片suffix。
3.7 func Contains
函數(shù)定義:
func Contains(b, subslice []byte) bool
判斷切片b是否包含子切片subslice。
3.8 func Count
函數(shù)定義:
func Count(s, sep []byte) int
Count計(jì)算s中有多少個(gè)不重疊的sep子切片。
3.9 func Index
函數(shù)定義:
func Index(s, sep []byte) int
子切片sep在s中第一次出現(xiàn)的位置,不存在則返回-1。
3.10 func IndexByte
函數(shù)定義:
func IndexByte(s []byte, c byte) int
字符c在s中第一次出現(xiàn)的位置,不存在則返回-1。
3.11 func ndexRune
函數(shù)定義:
func IndexRune(s []byte, r rune) int
unicode字符r的utf-8編碼在s中第一次出現(xiàn)的位置,不存在則返回-1。
3.12 func IndexAny
函數(shù)定義:
func IndexAny(s []byte, chars string) int
字符串chars中的任一utf-8編碼在s中第一次出現(xiàn)的位置,如不存在或者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
函數(shù)定義:
func IndexFunc(s []byte, f func(r rune) bool) int
IndexFunc 將 s 解釋為一系列UTF-8編碼的Unicode代碼點(diǎn)。它返回滿足 f(c) 的第一個(gè) Unicode 代碼點(diǎn)的 s 中的字節(jié)索引,否則返回 -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
函數(shù)定義:
func LastIndex(s, sep []byte) int
切片sep在字符串s中最后一次出現(xiàn)的位置,不存在則返回-1。
3.15 func LastIndexAny
func LastIndexAny(s []byte, chars string) int
字符串chars中的任一utf-8字符在s中最后一次出現(xiàn)的位置,如不存在或者chars為空字符串則返回-1。
3.16 func LastIndexFunc
func LastIndexFunc(s []byte, f func(r rune) bool) int
s中最后一個(gè)滿足函數(shù)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中每個(gè)單詞的首字母都改為標(biāo)題格式的拷貝。
BUG: Title用于劃分單詞的規(guī)則不能很好的處理Unicode標(biāo)點(diǎn)符號(hào)。
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
返回將所有字母都轉(zhuǎn)為對(duì)應(yīng)的小寫版本的拷貝。
fmt.Printf("%s", bytes.ToLower([]byte("Gopher"))) // gopher
3.19 func ToLowerSpecial
func ToLowerSpecial(_case unicode.SpecialCase, s []byte) []byte
ToLowerSpecial 將 s 視為 UTF-8 編碼的字節(jié)并返回一個(gè)副本,其中所有 Unicode 字母都映射到它們的小寫,優(yōu)先考慮特殊的大小寫規(guī)則。
package main
import (
"bytes"
"fmt"
"unicode"
)
func main() {
str := []byte("AHOJ VYVOJáR? GOLANG")
totitle := bytes.ToLowerSpecial(unicode.AzeriCase, str)
fmt.Println("Original : " + string(str))
fmt.Println("ToLower : " + string(totitle))
}
結(jié)果:
Original : AHOJ VYVOJáR? GOLANG
ToLower : ahoj vyvojári golang
3.20 func ToUpper
func ToUpper(s []byte) []byte
返回將所有字母都轉(zhuǎn)為對(duì)應(yīng)的大寫版本的拷貝。
3.21 func ToUpperSpecial
func ToUpperSpecial(_case unicode.SpecialCase, s []byte) []byte
使用_case規(guī)定的字符映射,返回將所有字母都轉(zhuǎn)為對(duì)應(yīng)的大寫版本的拷貝。
3.22 func ToTitle
func ToTitle(s []byte) []byte
返回將所有字母都轉(zhuǎn)為對(duì)應(yīng)的標(biāo)題版本的拷貝。
3.23 func ToTitleSpecial
func ToTitleSpecial(_case unicode.SpecialCase, s []byte) []byte
使用_case規(guī)定的字符映射,返回將所有字母都轉(zhuǎn)為對(duì)應(yīng)的標(biāo)題版本的拷貝。
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個(gè)b串聯(lián)形成的新的切片。
3.25 func Replace
func Replace(s, old, new []byte, n int) []byte
返回將 s 中 前n個(gè) 不重疊 old切片序列 都替換為 new 的新的切片拷貝,如果n<0會(huì)替換所有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))
}
結(jié)果:
oinky oinky oink
moo moo moo
3.26 func Map
func Map(mapping func(r rune) rune, s []byte) []byte
Map 根據(jù)映射函數(shù)返回字節(jié)切片s的所有字符修改后的副本。如果映射返回負(fù)值,則字符將從字符串中刪除而不會(huì)被替換。 s 和輸出中的字符被解釋為 UTF-8 編碼的 Unicode 代碼點(diǎn)。
package main
import (
"bytes"
"fmt"
)
func main() {
rot13 := func(r rune) rune {
switch {
case r >= 'A' && r <= 'Z':
return 'A' + (r-'A'+13)%26
case r >= 'a' && r <= 'z':
return 'a' + (r-'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碼值都去掉的子切片。(共用底層數(shù)組)
3.28 func TrimSpace
func TrimSpace(s []byte) []byte
返回將s前后端所有空白(unicode.IsSpace指定)都去掉的子切片。(共用底層數(shù)組)
3.29 func TrimFunc
func TrimFunc(s []byte, f func(r rune) bool) []byte
返回將s前后端所有滿足f的unicode碼值都去掉的子切片。(共用底層數(shù)組)
3.30 func TrimLeft
func TrimLeft(s []byte, cutset string) []byte
返回將s前端所有cutset包含的unicode碼值都去掉的子切片。(共用底層數(shù)組)
3.31 func TrimLeftFunc
func TrimLeftFunc(s []byte, f func(r rune) bool) []byte
返回將s前端所有滿足f的unicode碼值都去掉的子切片。(共用底層數(shù)組)
3.32 func TrimPrefix
func TrimPrefix(s, prefix []byte) []byte
返回去除s可能的前綴prefix的子切片。(共用底層數(shù)組)
3.33 func TrimRight
func TrimRight(s []byte, cutset string) []byte
返回將s后端所有cutset包含的unicode碼值都去掉的子切片。(共用底層數(shù)組)
3.34 func TrimRightFunc
func TrimRightFunc(s []byte, f func(r rune) bool) []byte
返回將s后端所有滿足f的unicode碼值都去掉的子切片。(共用底層數(shù)組)
3.35 func TrimSuffix
func TrimSuffix(s, suffix []byte) []byte
返回去除s可能的后綴suffix的子切片。(共用底層數(shù)組)
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 // 將每一個(gè)字符都+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確定,可以是一到多個(gè)連續(xù)的空白字符)分割的多個(gè)子切片。如果字符串全部是空白或者是空字符串的話,會(huì)返回空切片。
3.37 func FieldsFunc
func FieldsFunc(s []byte, f func(rune) bool) [][]byte
類似Fields,但使用函數(shù)f來確定分割符(滿足f的utf-8碼值)。如果字符串全部是分隔符或者是空字符串的話,會(huì)返回空切片。
3.38 func Split
func Split(s, sep []byte) [][]byte
用去掉s中出現(xiàn)的sep的方式進(jìn)行分割,會(huì)分割到結(jié)尾,并返回生成的所有[]byte切片組成的切片(每一個(gè)sep都會(huì)進(jìn)行一次切割,即使兩個(gè)sep相鄰,也會(huì)進(jìn)行兩次切割)。如果sep為空字符,Split會(huì)將s切分成每一個(gè)unicode碼值一個(gè)[]byte切片。
3.39 func SplitN
func SplitN(s, sep []byte, n int) [][]byte
用去掉s中出現(xiàn)的sep的方式進(jìn)行分割,會(huì)分割到最多n個(gè)子切片,并返回生成的所有[]byte切片組成的切片(每一個(gè)sep都會(huì)進(jìn)行一次切割,即使兩個(gè)sep相鄰,也會(huì)進(jìn)行兩次切割)。如果sep為空字符,Split會(huì)將s切分成每一個(gè)unicode碼值一個(gè)[]byte切片。參數(shù)n決定返回的切片的數(shù)目:
n > 0 : 返回的切片最多n個(gè)子字符串;最后一個(gè)子字符串包含未進(jìn)行切割的部分。
n == 0: 返回nil
n < 0 : 返回所有的子字符串組成的切片
3.40 func SplitAfter
func SplitAfter(s, sep []byte) [][]byte
用從s中出現(xiàn)的sep后面切斷的方式進(jìn)行分割,會(huì)分割到結(jié)尾,并返回生成的所有[]byte切片組成的切片(每一個(gè)sep都會(huì)進(jìn)行一次切割,即使兩個(gè)sep相鄰,也會(huì)進(jìn)行兩次切割)。如果sep為空字符,Split會(huì)將s切分成每一個(gè)unicode碼值一個(gè)[]byte切片。
3.41 func SplitAfterN
func SplitAfterN(s, sep []byte, n int) [][]byte
用從s中出現(xiàn)的sep后面切斷的方式進(jìn)行分割,會(huì)分割到最多n個(gè)子切片,并返回生成的所有[]byte切片組成的切片(每一個(gè)sep都會(huì)進(jìn)行一次切割,即使兩個(gè)sep相鄰,也會(huì)進(jìn)行兩次切割)。如果sep為空字符,Split會(huì)將s切分成每一個(gè)unicode碼值一個(gè)[]byte切片。參數(shù)n決定返回的切片的數(shù)目:
n > 0 : 返回的切片最多n個(gè)子字符串;最后一個(gè)子字符串包含未進(jìn)行切割的部分。
n == 0: 返回nil
n < 0 : 返回所有的子字符串組成的切片
3.42 func Join
func Join(s [][]byte, sep []byte) []byte
將一系列[]byte切片連接為一個(gè)[]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 // 存儲(chǔ)數(shù)據(jù)的byte切片
i int64 // current reading index => 當(dāng)前讀到的位置
prevRune int // index of previous rune; or < 0 => 前一個(gè)rune的索引
}
Reader類型通過從一個(gè)[]byte讀取數(shù)據(jù),實(shí)現(xiàn)了io.Reader、io.Seeker、io.ReaderAt、io.WriterTo、io.ByteScanner、io.RuneScanner接口。
4.1 func NewReader
func NewReader(b []byte) *Reader
NewReader創(chuàng)建一個(gè)從b讀取數(shù)據(jù)的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 中讀取字節(jié)到 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)
}
// 結(jié)果
r.Len() -> 11
r.Len() -> 6
hello
4.4 func (*Reader) ReadByte
func (r *Reader) ReadByte() (b byte, err error)
讀取一個(gè)字節(jié)
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)
}
// 結(jié)果
[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
如果上一個(gè)操作不是 ReadRune ,將報(bào)錯(cuò)。
如果是,將 ReadRune 讀取的影響復(fù)位。這里執(zhí)行下看看結(jié)果就明白意思了。
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實(shí)現(xiàn)了io.Seeker接口。
package main
import (
"fmt"
"strings"
)
func main() {
reader := strings.NewReader("Go語言學(xué)習(xí)園地")
reader.Seek(2, 0)
r, _, _ := reader.ReadRune()
fmt.Printf("%c\n", r)
}
// 結(jié)果
語
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實(shí)現(xiàn)了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的數(shù)據(jù)
off int // read at &buf[off], write at &buf[len(buf)] => buffer的目前讀取到的位置
lastRead readOp // last read operation, so that Unread* can work correctly. => 最后一次的讀取操作
}
Buffer是一個(gè)實(shí)現(xiàn)了讀寫方法的可變大小的字節(jié)緩沖。本類型的零值是一個(gè)空的可用于讀寫的緩沖。
5.1 func NewBuffer
func NewBuffer(buf []byte) *Buffer
NewBuffer使用buf作為初始內(nèi)容創(chuàng)建并初始化一個(gè)Buffer。本函數(shù)用于創(chuàng)建一個(gè)用于讀取已存在數(shù)據(jù)的buffer;也用于指定用于寫入的內(nèi)部緩沖的大小,此時(shí),buf應(yīng)為一個(gè)具有指定容量但長度為0的切片。buf會(huì)被作為返回值的底層緩沖切片。
大多數(shù)情況下,new(Buffer)(或只是聲明一個(gè)Buffer類型變量)就足以初始化一個(gè)Buffer了。
5.2 func NewBufferString
func NewBufferString(s string) *Buffer
NewBuffer使用s作為初始內(nèi)容創(chuàng)建并初始化一個(gè)Buffer。本函數(shù)用于創(chuàng)建一個(gè)用于讀取已存在數(shù)據(jù)的buffer。
大多數(shù)情況下,new(Buffer)(或只是聲明一個(gè)Buffer類型變量)就足以初始化一個(gè)Buffer了。
第一種方式
buffer := new(bytes.Buffer) // 使用new函數(shù)
第二種方式
buffer := bytes.NewBuffer([]byte{}) // 使用bytes包的NewBuffer函數(shù)
第三種方式
buffer := bytes.NewBufferString("") // 使用bytes包的NewBufferString函數(shù)
5.3 func (*Buffer) Len
func (b *Buffer) Len() int
返回緩沖中未讀取部分的字節(jié)長度;b.Len() == len(b.Bytes())。
5.4 func (*Buffer) Bytes
func (b *Buffer) Bytes() []byte
返回未讀取部分字節(jié)數(shù)據(jù)的切片,len(b.Bytes()) == b.Len()。如果中間沒有調(diào)用其他方法,修改返回的切片的內(nèi)容會(huì)直接改變Buffer的內(nèi)容。
5.5 func (*Buffer) String
func (b *Buffer) String() string
將未讀取部分的字節(jié)數(shù)據(jù)作為字符串返回,如果b是nil指針,會(huì)返回空字符串。
5.6 func (*Buffer) Grow
func (b *Buffer) Grow(n int)
必要時(shí)會(huì)增加緩沖的容量,以保證n字節(jié)的剩余空間。調(diào)用Grow(n)后至少可以向緩沖中寫入n字節(jié)數(shù)據(jù)而無需申請(qǐng)內(nèi)存。如果n小于零或者不能增加容量都會(huì)panic。
5.7 func (*Buffer) Read
func (b *Buffer) Read(p []byte) (n int, err error)
Read方法從緩沖中讀取數(shù)據(jù)直到緩沖中沒有數(shù)據(jù)或者讀取了len(p)字節(jié)數(shù)據(jù),將讀取的數(shù)據(jù)寫入p。返回值n是讀取的字節(jié)數(shù),除非緩沖中完全沒有數(shù)據(jù)可以讀取并寫入p,此時(shí)返回值err為io.EOF;否則err總是nil。
5.8 func (*Buffer) Next
func (b *Buffer) Next(n int) []byte
返回未讀取部分前n字節(jié)數(shù)據(jù)的切片,并且移動(dòng)讀取位置,就像調(diào)用了Read方法一樣。如果緩沖內(nèi)數(shù)據(jù)不足,會(huì)返回整個(gè)數(shù)據(jù)的切片。切片只在下一次調(diào)用b的讀/寫方法前才合法。
5.9 func (*Buffer) ReadByte
func (b *Buffer) ReadByte() (c byte, err error)
ReadByte讀取并返回緩沖中的下一個(gè)字節(jié)。如果沒有數(shù)據(jù)可用,返回值err為io.EOF。
5.10 func (*Buffer) UnreadByte
func (b *Buffer) UnreadByte() error
UnreadByte吐出最近一次讀取操作讀取的最后一個(gè)字節(jié)。如果最后一次讀取操作之后進(jìn)行了寫入,本方法會(huì)返回錯(cuò)誤。
5.11 func (*Buffer) ReadRune
func (b *Buffer) ReadRune() (r rune, size int, err error)
ReadRune讀取并返回緩沖中的下一個(gè)utf-8碼值。如果沒有數(shù)據(jù)可用,返回值err為io.EOF。如果緩沖中的數(shù)據(jù)是錯(cuò)誤的utf-8編碼,本方法會(huì)吃掉一字節(jié)并返回(U+FFFD, 1, nil)。
5.12 func (*Buffer) UnreadRune
func (b *Buffer) UnreadRune() error
UnreadRune吐出最近一次調(diào)用ReadRune方法讀取的unicode碼值。如果最近一次讀寫操作不是ReadRune,本方法會(huì)返回錯(cuò)誤。(這里就能看出來UnreadRune比UnreadByte嚴(yán)格多了)
5.13 func (*Buffer) ReadBytes
func (b *Buffer) ReadBytes(delim byte) (line []byte, err error)
ReadBytes讀取直到第一次遇到delim字節(jié),返回一個(gè)包含已讀取的數(shù)據(jù)和delim字節(jié)的切片。如果ReadBytes方法在讀取到delim之前遇到了錯(cuò)誤,它會(huì)返回在錯(cuò)誤之前讀取的數(shù)據(jù)以及該錯(cuò)誤(一般是io.EOF)。當(dāng)且僅當(dāng)ReadBytes方法返回的切片不以delim結(jié)尾時(shí),會(huì)返回一個(gè)非nil的錯(cuò)誤。
5.14 func (*Buffer) ReadString
func (b *Buffer) ReadString(delim byte) (line string, err error)
ReadString讀取直到第一次遇到delim字節(jié),返回一個(gè)包含已讀取的數(shù)據(jù)和delim字節(jié)的字符串。如果ReadString方法在讀取到delim之前遇到了錯(cuò)誤,它會(huì)返回在錯(cuò)誤之前讀取的數(shù)據(jù)以及該錯(cuò)誤(一般是io.EOF)。當(dāng)且僅當(dāng)ReadString方法返回的切片不以delim結(jié)尾時(shí),會(huì)返回一個(gè)非nil的錯(cuò)誤。
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èi)容寫入緩沖中,如必要會(huì)增加緩沖容量。返回值n為len(p),err總是nil。如果緩沖變得太大,Write會(huì)采用錯(cuò)誤值ErrTooLarge引發(fā)panic。
5.16 func (*Buffer) WriteString
func (b *Buffer) WriteString(s string) (n int, err error)
Write將s的內(nèi)容寫入緩沖中,如必要會(huì)增加緩沖容量。返回值n為len(p),err總是nil。如果緩沖變得太大,Write會(huì)采用錯(cuò)誤值ErrTooLarge引發(fā)panic。
5.17 func (*Buffer) WriteByte
func (b *Buffer) WriteByte(c byte) error
WriteByte將字節(jié)c寫入緩沖中,如必要會(huì)增加緩沖容量。返回值總是nil,但仍保留以匹配bufio.Writer的WriteByte方法。如果緩沖太大,WriteByte會(huì)采用錯(cuò)誤值ErrTooLarge引發(fā)panic。
5.18 func (*Buffer) WriteRune
func (b *Buffer) WriteRune(r rune) (n int, err error)
WriteByte將unicode碼值r的utf-8編碼寫入緩沖中,如必要會(huì)增加緩沖容量。返回值總是nil,但仍保留以匹配bufio.Writer的WriteRune方法。如果緩沖太大,WriteRune會(huì)采用錯(cuò)誤值ErrTooLarge引發(fā)panic。
5.19 func (*Buffer) ReadFrom
func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)
ReadFrom從r中讀取數(shù)據(jù)直到結(jié)束并將讀取的數(shù)據(jù)寫入緩沖中,如必要會(huì)增加緩沖容量。返回值n為從r讀取并寫入b的字節(jié)數(shù);會(huì)返回讀取時(shí)遇到的除了io.EOF之外的錯(cuò)誤。如果緩沖太大,ReadFrom會(huì)采用錯(cuò)誤值ErrTooLarge引發(fā)panic。
5.20 func (*Buffer) WriteTo
func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)
WriteTo從緩沖中讀取數(shù)據(jù)直到緩沖內(nèi)沒有數(shù)據(jù)或遇到錯(cuò)誤,并將這些數(shù)據(jù)寫入w。返回值n為從b讀取并寫入w的字節(jié)數(shù);返回值總是可以無溢出的寫入int類型,但為了匹配io.WriterTo接口設(shè)為int64類型。從b讀取是遇到的非io.EOF錯(cuò)誤及寫入w時(shí)遇到的錯(cuò)誤都會(huì)終止本方法并返回該錯(cuò)誤。
5.21 func (*Buffer) Truncate
func (b *Buffer) Truncate(n int)
丟棄緩沖中除前n字節(jié)數(shù)據(jù)外的其它數(shù)據(jù),如果n小于零或者大于緩沖容量將panic。文章來源:http://www.zghlxwxcb.cn/news/detail-469486.html
5.22 func (*Buffer) Reset
func (b *Buffer) Reset()
Reset重設(shè)緩沖,因此會(huì)丟棄全部內(nèi)容,等價(jià)于
b.Truncate(0)
。文章來源地址http://www.zghlxwxcb.cn/news/detail-469486.html
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
}
到了這里,關(guān)于Golang標(biāo)準(zhǔn)庫之bytes介紹的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!