bytes.go
包含很多处理[]byte的函数。做到看到函数名就能想起它是干嘛的就行了吧,这就算会用这个这个package了。还要知道实现原理,才能对这个函数的效率有个大致把握。
其中涉及编码的函数都仅支持UTF-8
其中子串查找类操作:
Count Contains ContainsRune IndexRune都依赖Index IndexByte
Index IndexByte有实现类似的 LastIndex LastIndexByte
IndexByte汇编语言实现
func Index(s, sep []byte) int
根据sep的长度选择indexByte 或者暴力解法 或者rabin-karp算法
分切类操作:
Split SplitN SplitAfter SplitAfterNFields
拼接类操作:
Join 将[][]byte拼接成[]byte,拼接位置可以插入指定[]byteRepeat
替换类操作:
Replace ReplaceAllToUpper 、ToLower 、Title(注意和ToTitle完全不一样)Map操作比较有意思,签名是 func Map(mapping func(r rune) rune, s []byte) []byte 需要传入回调函数
[]byte到[]rune的类型转换正确姿势:
func Runes(s []byte) []rune
下面的方式会消耗更多空间
byts := []byte("The")runes := []rune(string(byts))
buffer.go
提供数据结构buffer及相关算法。buffer显然需要这样4个指针。
开始p2与p1重叠,从buffer读出数据后p2右移指向新的读取位置。
写入n个字节之前要从p3-p4之间预留n个字节的空间:
func (*buffer)grow(n)if (p2与p3重叠,且大于p1)将p2、p3移至p1处if (p4-p3>=n)直接向buffer写入数据后p3右移指向新的写入位置。returnif (未读数据+n <= 数组长度一半) //不用分配更大数组把未读数据滑动到数组开始else if (2*数组长度+n > maxInt)panic(ErrTooLarge)elsemakeSlice(2*数组长度+n)copy数据至新数组
bytes.Buffer是byte缓冲器,核心结构是[]byte
type Buffer struct {buf []byte // contents are the bytes buf[off : len(buf)]off int // read at &buf[off], write at &buf[len(buf)]lastRead readOp // last read operation, so that Unread* can work correctly.}
buf切片内部指针、len、cap对应p1、p3、p4
off对应p2
reader.go
提供数据结构reader及相关算法。
