BufReader read bytes fail a feature or a bug

use std::io::{BufRead, BufReader, Read};

fn main() {
    let values: [u8; 10000] = [1; 10000];
    let mut reader = BufReader::new(values.as_slice());
    let mut i = 0;
    println!("reader capacity: {}", reader.capacity());
    while !reader.fill_buf().unwrap().is_empty() {
        let mut b: [u8; 1] = [0; 1];
        let n = reader.read(&mut b).unwrap();
        assert_eq!(1, n);
        i += 1;
        if i == 8191 {
            let mut b: [u8; 2] = [0; 2];
            let n = reader.read(&mut b).unwrap();
            println!("{},{:?}, {}", i, b, n);
            assert_eq!(n, 2);

BufReader capacity default is 8192. when there is 1 byte in inner buffer read 2 byte only return 1 . i don't know this is a feature or a bug.

It's perfectly valid for anything implementing the Read trait to return less than a full buffer on any given call to its read method. Sometimes there's no other option (at the end of a stream), but other times it's just whenever that makes the implementation simpler.


You should have read the documentation.

You are looking for the read_exact() method.


Also in the docs but not very intuitive, full_buf only fills when empty.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.