dongya8378 2013-08-27 14:22
浏览 62
已采纳

阅读超出缓冲区

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.

  • 写回答

2条回答 默认 最新

  • doupi1532 2013-08-27 14:35
    关注

    Your expectations are not based on any documented behavior of bufio.Reader. If you want "Read to always give the amount of bytes len(byteArray)" you must use 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, 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, string(d))
    }
    

    Playground


    Output:

    First read got 12 bytes: some length 
    Second read got 12 bytes: test string 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题