原本只想用用bufio,但是網(wǎng)上文章沒(méi)有一個(gè)寫清楚bufio到底怎么用,每個(gè)方法具體干了什么,搞不明白原理就不敢亂用,還好有源碼,自己來(lái)分析最清楚。
Reader分析
func NewReaderSize(rd io.Reader, size int) *Reader {
// Is it already a Reader?
b, ok := rd.(*Reader)
if ok && len(b.buf) >= size {
return b
}
if size < minReadBufferSize { //minReadBufferSize==16
size = minReadBufferSize
}
r := new(Reader)
r.reset(make([]byte, size), rd)
return r
}
// NewReader returns a new Reader whose buffer has the default size.
func NewReader(rd io.Reader) *Reader {
return NewReaderSize(rd, defaultBufSize)
}
一開始傳入io.Reader創(chuàng)建bufio.Reader,默認(rèn)defaultBufSize為4096字節(jié)也就是4K字節(jié)。
// fill reads a new chunk into the buffer.
func (b *Reader) fill() {
// Slide existing data to beginning.
if b.r > 0 { //把buf剩余可讀的數(shù)據(jù)復(fù)制到最前
copy(b.buf, b.buf[b.r:b.w])
b.w -= b.r
b.r = 0
}
if b.w >= len(b.buf) {//緩存已經(jīng)溢出了
panic("bufio: tried to fill full buffer")
}
//maxConsecutiveEmptyReads == 100
// Read new data: try a limited number of times.
for i := maxConsecutiveEmptyReads; i > 0; i-- {
n, err := b.rd.Read(b.buf[b.w:]) //從io中讀取數(shù)據(jù)寫入緩存
if n < 0 {
panic(errNegativeRead)
}
b.w += n //更新寫入緩存的長(zhǎng)度
if err != nil {
b.err = err
return
}
if n > 0 {
return
}
// n== 0時(shí)會(huì)循環(huán)嘗試從io中讀取,最多100次
}
b.err = io.ErrNoProgress //讀了100次,n都為0
}
fill()把剩余未讀長(zhǎng)度的數(shù)據(jù)復(fù)制到緩存頭部并且r重置為0,相當(dāng)于把未讀數(shù)據(jù)移動(dòng)到頭部。同時(shí)盡量從io中讀取數(shù)據(jù)寫入緩存,有可能不能寫滿。
// ReadByte reads and returns a single byte.
// If no byte is available, returns an error.
func (b *Reader) ReadByte() (byte, error) {
b.lastRuneSize = -1
for b.r == b.w { //緩存中無(wú)數(shù)據(jù)可讀
if b.err != nil {
return 0, b.readErr()
}
b.fill() // buffer is empty,從io中fill數(shù)據(jù)
}
c := b.buf[b.r]//此時(shí)肯定有數(shù)據(jù)了,取r位置的一個(gè)字節(jié)
b.r++ //r游標(biāo)移動(dòng)一個(gè)字節(jié)
b.lastByte = int(c)
return c, nil
}
ReadByte()從緩存中讀取一個(gè)字節(jié),如果緩存中沒(méi)有數(shù)據(jù)則嘗試從io中填充數(shù)據(jù)。最后返回讀取到的一個(gè)字節(jié)的內(nèi)容
// Read reads data into p.
// It returns the number of bytes read into p.
// The bytes are taken from at most one Read on the underlying Reader,
// hence n may be less than len(p).
// At EOF, the count will be zero and err will be io.EOF.
func (b *Reader) Read(p []byte) (n int, err error) {
n = len(p)
if n == 0 {
return 0, b.readErr()
}
if b.r == b.w {//緩存中無(wú)數(shù)據(jù)可讀
if b.err != nil {
return 0, b.readErr()
}
if len(p) >= len(b.buf) { //p的空間大于等于緩存
// Large read, empty buffer.
// Read directly into p to avoid copy.
n, b.err = b.rd.Read(p)//直接從io中把數(shù)據(jù)讀取到p中
if n < 0 {
panic(errNegativeRead)
}
if n > 0 {
b.lastByte = int(p[n-1])
b.lastRuneSize = -1
}
return n, b.readErr()
}
// One read.
// Do not use b.fill, which will loop.
// 無(wú)數(shù)據(jù)可讀,表示buf中數(shù)據(jù)無(wú)用了則重置r和w的游標(biāo)
b.r = 0
b.w = 0
n, b.err = b.rd.Read(b.buf)//從io中讀取到緩存
if n < 0 {
panic(errNegativeRead)
}
if n == 0 {
return 0, b.readErr()
}
b.w += n//緩存寫入了多少數(shù)據(jù)
}
// copy as much as we can
n = copy(p, b.buf[b.r:b.w])//緩存中數(shù)據(jù)可讀數(shù)據(jù)讀取到p
b.r += n //讀了多少
b.lastByte = int(b.buf[b.r-1])
b.lastRuneSize = -1
return n, nil
}
Read(p []byte):
當(dāng)緩存中沒(méi)有可讀數(shù)據(jù)時(shí)有兩種情況:
情況1. 當(dāng)p的空間大于等于緩存時(shí),直接從io中把數(shù)據(jù)讀取到p。
情況2. 當(dāng)p的空間小于緩存時(shí),重置緩存游標(biāo),盡量從io中讀取數(shù)據(jù)到緩存 ,然后再?gòu)木彺嬷袕?fù)制到p里。
當(dāng)緩存中有可讀數(shù)據(jù)時(shí),直接從緩存中把可讀數(shù)據(jù)復(fù)制到p中,此時(shí)不會(huì)去讀取io。
p的空間有可能被填滿,也有可能不滿,返回的n說(shuō)明讀取了多少個(gè)字節(jié)。
// Peek returns the next n bytes without advancing the reader. The bytes stop
// being valid at the next read call. If Peek returns fewer than n bytes, it
// also returns an error explaining why the read is short. The error is
// ErrBufferFull if n is larger than b's buffer size.
func (b *Reader) Peek(n int) ([]byte, error) {
if n < 0 {
return nil, ErrNegativeCount
}
//剩余可讀小于n而且小于緩存時(shí)從io里fill數(shù)據(jù)到緩存
for b.w-b.r < n && b.w-b.r < len(b.buf) && b.err == nil {
b.fill() // b.w-b.r < len(b.buf) => buffer is not full
}
//n比緩存大,返回可讀的緩存切片,而且錯(cuò)誤值為ErrBufferFull
if n > len(b.buf) {
return b.buf[b.r:b.w], ErrBufferFull
}
// 0 <= n <= len(b.buf)
var err error
if avail := b.w - b.r; avail < n {
// not enough data in buffer
//緩存的可讀數(shù)據(jù)不夠讀,返回可以讀的緩存切片及錯(cuò)誤值ErrBufferFull
n = avail
err = b.readErr()
if err == nil {
err = ErrBufferFull
}
}
//如果緩存的可讀數(shù)據(jù)足夠就返回可讀緩存切片和空錯(cuò)誤
return b.buf[b.r : b.r+n], err
}
Peek(n int):
先從io中填充緩存。
如果要讀的n比緩存大返回錯(cuò)誤值ErrBufferFull。
如果n小于等于緩存,且可讀數(shù)據(jù)不夠讀返回ErrBufferFull或者io讀錯(cuò)誤。
如果有可夠讀的數(shù)據(jù)返回的錯(cuò)誤為空。
不管怎樣都會(huì)返回緩存可讀取的切片但是沒(méi)有移動(dòng)讀游標(biāo),修改返回的切片會(huì)影響緩存中的數(shù)據(jù)。
// Buffered returns the number of bytes that can be read from the current buffer.
func (b *Reader) Buffered() int { return b.w - b.r }//可讀長(zhǎng)度
// Discard skips the next n bytes, returning the number of bytes discarded.
//
// If Discard skips fewer than n bytes, it also returns an error.
// If 0 <= n <= b.Buffered(), Discard is guaranteed to succeed without
// reading from the underlying io.Reader.
func (b *Reader) Discard(n int) (discarded int, err error) {
if n < 0 {
return 0, ErrNegativeCount
}
if n == 0 {
return
}
remain := n
for {
skip := b.Buffered()
if skip == 0 {//沒(méi)可讀先f(wàn)ill填充
b.fill()
skip = b.Buffered()
}
if skip > remain {
skip = remain
}
b.r += skip //讀游標(biāo)直接跳過(guò)skip個(gè)字節(jié)
remain -= skip
if remain == 0 {//成功跳過(guò)請(qǐng)求的字節(jié)長(zhǎng)度
return n, nil
}
if b.err != nil {//出錯(cuò)了,返回剩下多少個(gè)字節(jié)沒(méi)跳過(guò)和錯(cuò)誤
return n - remain, b.readErr()
}
}
}
Discard(n int) :
跳過(guò)n個(gè)字節(jié)不讀取,一直循環(huán)到成功跳過(guò)或者出現(xiàn)錯(cuò)誤。
Reader的其他方法我一般不用,所以也不分析了。
總結(jié):
Peek返回錯(cuò)誤不為空時(shí),一種情況是你Peek的長(zhǎng)度比緩存都大,那么數(shù)據(jù)永遠(yuǎn)不夠,所以傳入?yún)?shù)時(shí)要注意別比緩存大。
別一種情況是,從io里嘗試讀數(shù)據(jù)了但還是準(zhǔn)備不夠你需要的長(zhǎng)度,比如網(wǎng)絡(luò)tcp的數(shù)據(jù)一開始沒(méi)有到達(dá),等下一輪你再調(diào)用Peek時(shí)可能緩存就足夠你讀了。
其實(shí)就算有錯(cuò)誤也會(huì)返回你可讀取的切片。
如果錯(cuò)誤為空,恭喜你,數(shù)據(jù)都準(zhǔn)備好啦。
Peek不會(huì)移動(dòng)讀游標(biāo),如果直接使用Peek返回的切片可以配合Discard來(lái)跳過(guò)指定字節(jié)的數(shù)據(jù)不再讀取也就是移動(dòng)讀游標(biāo)。
Read盡量先從緩存中讀取數(shù)據(jù)。當(dāng)前緩存無(wú)數(shù)據(jù)可讀時(shí)先從io中讀取填充到緩存里,然后從緩存中復(fù)制。返回讀取到的數(shù)據(jù)長(zhǎng)度不一定,小于或者等于Read要求的長(zhǎng)度。
想跳過(guò)n個(gè)字節(jié)不讀取,使用Discard。
使用NewReader初始化時(shí)默認(rèn)緩存為4096字節(jié),在某些情況下可能太大浪費(fèi)內(nèi)存或者太小不夠用,最好還是使用NewReaderSize根據(jù)情況自定義緩存大小。
Writer
有空再寫