Scanner.Buffer - 最大值对自定义拆分没有影响?

Scanner.Buffer - max value has no effect on custom Split?

为了减少默认的 64k 扫描仪缓冲区 (对于内存不足的微型计算机),我尝试使用此缓冲区和自定义拆分功能:

scanner.Buffer(make([]byte, 5120), 64)
scanner.Split(Scan64Bytes)

这里我注意到第二个缓冲区参数“max”没有效果。如果我改为插入例如015120bufio.MaxScanTokenSize[=31= 】,我看不出有什么区别。 只有第一个参数“buf”有结果。如果容量太小,扫描不完整,如果容量太大,B/op benchmem 值会增加。

来自文档:

The maximum token size is the larger of max and cap(buf). If max <= cap(buf), Scan will use this buffer only and do no allocation.

我不明白哪个是正确的最大值。你能给我解释一下吗?

Go Playground

package main

import (
    "bufio"
    "bytes"
    "fmt"
)

func Scan64Bytes(data []byte, atEOF bool) (advance int, token []byte, err error) {
    if len(data) < 64 {
        return 0, data[0:], bufio.ErrFinalToken
    }
    return 64, data[0:64], nil
}

func main() {
    // improvised source of the same size:
    cmdstd := bytes.NewReader(make([]byte, 5120))
    scanner := bufio.NewScanner(cmdstd)

    // I guess 64 is the correct max arg:
    scanner.Buffer(make([]byte, 5120), 64)
    scanner.Split(Scan64Bytes)

    for i := 0; scanner.Scan(); i++ {
        fmt.Printf("%v: %v\r\n", i, scanner.Bytes())
    }

    if err := scanner.Err(); err != nil {
        fmt.Println(err)
    }
}

max value has no effect on custom Split?

不,不拆分也是一样的结果。但是如果没有 split 和 ErrFinalToken,这是不可能的:

//your reader/input
cmdstd := bytes.NewReader(make([]byte, 5120))

// your scanner buffer size
scanner.Buffer(make([]byte, 5120), 64)

来自扫描仪的缓冲区大小应该更大。这就是我设置 buf 和 max 的方式:

scanner.Buffer(make([]byte, 5121), 5120)