欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

golang中bufio.SplitFunc的深入理解

程序员文章站 2023-04-08 13:24:24
前言 bufio模块是golang标准库中的模块之一,主要是实现了一个读写的缓存,用于对数据的读取或者写入操作。该模块在多个涉及io的标准库中被使用,比如http模块...

前言

bufio模块是golang标准库中的模块之一,主要是实现了一个读写的缓存,用于对数据的读取或者写入操作。该模块在多个涉及io的标准库中被使用,比如http模块中使用buffio来完成网络数据的读写,压缩文件的zip模块利用bufio来操作文件数据的读写等。

golang的bufio包里面定以的splitfunc是一个比较重要也比较难以理解的东西,本文希望通过结合简单的实例介绍splitfunc的工作原理以及如何实现一个自己的splitfunc。

一个例子

在bufio包里面定义了一些常用的工具比如scanner,你可能需要读取用户在标准输入里面输入的一些东西,比如我们做一个复读机,读取用户的每一行输入,然后打印出来:

package main
import (
 "bufio"
 "fmt"
 "os"
)
func main() {
 scanner := bufio.newscanner(os.stdin)
 scanner.split(bufio.scanlines)
 for scanner.scan() {
 fmt.println(scanner.text())
 }
}

这个程序很简单,os.stdin实现了io.reader接口,我们从这个reader创建了一个scanner,设置分割函数为bufio.scanlines,然后for循环,每次读到一行数据就将文本内容打印出来。麻雀虽小五脏俱全,这个小程序虽然简单,却引出了我们今天要介绍的对象: bufio.splitfunc,它的定义是这个样子的:

package "buffio"
type splitfunc func(data []byte, ateof bool) (advance int, token []byte, err error)

golang官方文档的描述是这个样子的:

splitfunc is the signature of the split function used to tokenize the input. the arguments are an initial substring of the remaining unprocessed data and a flag, ateof, that reports whether the reader has no more data to give. the return values are the number of bytes to advance the input and the next token to return to the user, if any, plus an error, if any.

scanning stops if the function returns an error, in which case some of the input may be discarded.

otherwise, the scanner advances the input. if the token is not nil, the scanner returns it to the user. if the token is nil, the scanner reads more data and continues scanning; if there is no more data--if ateof was true--the scanner returns. if the data does not yet hold a complete token, for instance if it has no newline while scanning lines, a splitfunc can return (0, nil, nil) to signal the scanner to read more data into the slice and try again with a longer slice starting at the same point in the input.

the function is never called with an empty data slice unless ateof is true. if ateof is true, however, data may be non-empty and, as always, holds unprocessed text.

英文!参数这么多!返回值这么多!好烦!不知道各位读者遇到这种文档会不会有这种感觉...正式由于这种情况,我才决定写一篇文章介绍一下splitfunc的具体工作原理,用一种通俗的方式结合具体实例加以说明,希望对读者有所帮助。
好了,废话少说,开始正题吧!

scanner和splitfunc的工作机制

package "buffio"
type splitfunc func(data []byte, ateof bool) (advance int, token []byte, err error)

scanner是有缓存的,意思是scanner底层维护了一个slice用来保存已经从reader中读取的数据,scanner会调用我们设置splitfunc,将缓冲区内容(data)和是否已经输入完了(ateof)以参数的形式传递给splitfunc,而splitfunc的职责就是根据上述的两个参数返回下一次scan需要前进几个字节(advance),分割出来的数据(token),以及错误(err)。

这是一个通信双向的过程,scanner告诉我们的splitfunc已经扫描到的数据和是否到结尾了,我们的splitfunc则根据这些信息将分割的结果返回和下次扫描需要前进的位置返回给scanner。用一个例子来说明:

package main
import (
 "bufio"
 "fmt"
 "strings"
)
func main() {
 input := "abcdefghijkl"
 scanner := bufio.newscanner(strings.newreader(input))
 split := func(data []byte, ateof bool) (advance int, token []byte, err error) {
  fmt.printf("%t\t%d\t%s\n", ateof, len(data), data)
  return 0, nil, nil
 }
 scanner.split(split)
 buf := make([]byte, 2)
 scanner.buffer(buf, bufio.maxscantokensize)
 for scanner.scan() {
  fmt.printf("%s\n", scanner.text())
 }
}

输出

false 2 ab
false 4 abcd
false 8 abcdefgh
false 12 abcdefghijkl
true 12 abcdefghijkl

这里我们把缓冲区的初始大小设置为了2,不够的时候会扩展为原来的2倍,最大为bufio.maxscantokensize,这样一开始扫描2个字节,我们的缓冲区就满了,reader的内容还没有读取到eof,然后split函数执行,输出:

false 2 ab

紧接着函数返回 0, nil, nil这个返回值告诉scanner数据不够,下次读取的位置前进0位,需要继续从reader里面读取,此时因为缓冲区满了,所以容量扩展为2 * 2 = 4,reader的内容还没有读取到eof,输出

false 4 abcd

重复上述步骤,一直到最后全部内容读取完了,eof此时变成了true

true 12 abcdefghijkl

看了上面的过程是不是对splitfunc的工作原来有了一点理解了呢?再回头看一下golang的官方文档有没有觉得稍微理解了一点?下面是bufio.scanlines的实现,读者可以自己研究一下该函数是如何工作的

标准库里的scanlines

func scanlines(data []byte, ateof bool) (advance int, token []byte, err error) {
 // 表示我们已经扫描到结尾了
 if ateof && len(data) == 0 {
  return 0, nil, nil
 }
 // 找到\n的位置
 if i := bytes.indexbyte(data, '\n'); i >= 0 {
  // 把下次开始读取的位置向前移动i + 1位
  return i + 1, dropcr(data[0:i]), nil
 }
 // 这里处理的reader内容全部读取完了,但是内容不为空,所以需要把剩余的数据返回
 if ateof {
  return len(data), dropcr(data), nil
 }
 // 表示现在不能分割,向reader请求更多的数据
 return 0, nil, nil
}

参考

in-depth introduction to bufio.scanner in golang

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。