0

I have a buffer of size bufferSize from which I read in chunks of blockSize, however, this yields some (to me) unexpected behavior, when the blockSize goes beyond the bufferSize.

I've put the code here:

http://play.golang.org/p/Ra2jicYHPu

Why does the second chunk only give 4 bytes? What's happening here?

I'd expect Read to always give the amount of bytes len(byteArray), and if it goes beyond the buffer, it'll handle that situation by setting the pointer in the buffer to after byteArray, and putting the rest of the buffer + whatever is beyond until the new buffer pointer.

4

2 回答 2

1

您的期望并非基于任何记录在案的bufio.Reader. 如果您希望“读取始终给出字节数 len(byteArray)” ,则必须使用io.ReadAtLeast

package main

import (
        "bufio"
        "fmt"
        "io"
        "strings"
)

const bufSize = 10
const blockSize = 12

func main() {
        s := strings.NewReader("some length test string buffer boom")
        buffer := bufio.NewReaderSize(s, bufSize)

        b := make([]byte, blockSize)
        n, err := io.ReadAtLeast(buffer, b, blockSize)
        if err != nil {
                fmt.Println(err)
        }

        fmt.Printf("First read got %d bytes: %s\n", n, string(b))

        d := make([]byte, blockSize)
        n, err = io.ReadAtLeast(buffer, d, blockSize)
        if err != nil {
                fmt.Println(err)
        }

        fmt.Printf("Second read got %d bytes: %s\n", n, string(d))
}

操场


输出:

First read got 12 bytes: some length 
Second read got 12 bytes: test string 
于 2013-08-27T14:35:59.820 回答
0

1.查看buffio.NewReaderSize的代码

func NewReaderSize(rd io.Reader, size int) *Reader {
    // Is it already a Reader?
    b, ok := rd.(*Reader)
    if ok && len(b.buf) >= size {
        return b
    }
    if size < minReadBufferSize {
        size = minReadBufferSize
    }
    return &Reader{
        buf:          make([]byte, size),
        rd:           rd,
        lastByte:     -1,
        lastRuneSize: -1,
    }
}

strings.NewReader 返回一个strings.Reader,所以缓冲区的(由bufio.NewReaderSize 返回)buf 有minReadBufferSize(val 为16) 2.见bufio.Read 的代码

func (b *Reader) Read(p []byte) (n int, err error) {
    ……
    copy(p[0:n], b.buf[b.r:])
    b.r += n
    b.lastByte = int(b.buf[b.r-1])
    b.lastRuneSize = -1
    return n, nil
}

复制src是b.buf[ br :],当你第一次Read时,br=12,……

于 2013-08-28T04:28:30.123 回答