Golang源码阅读 Bufio阅读
基本实现 实现带缓存的I/O模块 对io.Reader和io.Writer进行封装 实现带缓存 对字符的I/O操作友好 Reader(缓存输入) 实现了一个带缓存的io.Reader
数据结构 1 2 3 4 5 6 7 8 type Reader struct { buf []byte // 缓存 rd io.Reader // 被包装的io.Reader对象 r, w int // buf切片上的索引,r代表读取的索引,w代表写入的索引 err error // 用来存储该Reader在执行中遇到的error lastByte int // 已读取的最后一个字节; -1 代表无效 lastRuneSize int // 已读取的最后一个rune; -1 代表无效 } 默认信息 1 2 const minReadBufferSize = 16 // buf最小长度为16字节 const maxConsecutiveEmptyReads = 100 // 一次读取,在连续100次没读取到会认为失败 关键代码逻辑 func (b *Reader) fill() 读取新的一个数据块,尽可能读满buf;只会读取成功读取一次,允许maxConsecutiveEmptyReads次读取失败,但是第一次读取成功后就不再读取,返回;……