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 SplitAfterN
Fields

拼接类操作:

Join 将[][]byte拼接成[]byte,拼接位置可以插入指定[]byte
Repeat

替换类操作:

Replace ReplaceAll
ToUpper 、ToLower 、Title(注意和ToTitle完全不一样)
Map操作比较有意思,签名是 func Map(mapping func(r rune) rune, s []byte) []byte 需要传入回调函数

[]byte到[]rune的类型转换正确姿势:

func Runes(s []byte) []rune
下面的方式会消耗更多空间

  1. byts := []byte("The")
  2. runes := []rune(string(byts))

buffer.go

提供数据结构buffer及相关算法。buffer显然需要这样4个指针。
image.png
开始p2与p1重叠,从buffer读出数据后p2右移指向新的读取位置。

写入n个字节之前要从p3-p4之间预留n个字节的空间:

  1. func (*buffer)grow(n)
  2. if (p2与p3重叠,且大于p1)
  3. 将p2、p3移至p1处
  4. if (p4-p3>=n)
  5. 直接向buffer写入数据后p3右移指向新的写入位置。
  6. return
  7. if (未读数据+n <= 数组长度一半) //不用分配更大数组
  8. 把未读数据滑动到数组开始
  9. else if (2*数组长度+n > maxInt)
  10. panic(ErrTooLarge)
  11. else
  12. makeSlice(2*数组长度+n)
  13. copy数据至新数组

bytes.Buffer是byte缓冲器,核心结构是[]byte

  1. type Buffer struct {
  2. buf []byte // contents are the bytes buf[off : len(buf)]
  3. off int // read at &buf[off], write at &buf[len(buf)]
  4. lastRead readOp // last read operation, so that Unread* can work correctly.
  5. }

buf切片内部指针、len、cap对应p1、p3、p4
off对应p2

reader.go

提供数据结构reader及相关算法。