BufReader documentation precision

Hi! New to rust programming and today I spent time on std::io::BufReader documentation.
I stopped on the following sentence :

BufReader<R> can improve the speed of programs that make small and repeated read calls to the same file or network socket. It does not help when reading very large amounts at once, or reading just one or a few times. It also provides no advantage when reading from a source that is already in memory, like a Vec<u8>.

I understand how a buffered reader works with large and infrequent reads but I do not understand the following point:

It also provides no advantage when reading from a source that is already in memory, like a Vec<u8>.

What does it mean ? A BufReader is not supposed to read from file only ?

For example, if I have a custom file format to parse:

1
1
2
3
5
8
13
21
...

This kind of format will be loaded in memory into a Vec<u8>. Does the std::io::BufReader<R> documentation states that I should not use a BufReader ?

Thanks for your help.
-logan

What does it mean ? A BufReader is not supposed to read from file only ?

A BufReader is a wrapper around whatever happens to implement io::Read, which is by no means limited to files or sockets. For example, it is implemented for &[u8] which is what documentation is warning you about (to read from Vec you will really need to first convert it into slice): slice already lives in memory, there is absolutely no need to copy its contents into another region of memory. So if you know that you are reading from a slice do not use BufReader.

This advice has nothing to do with what you are reading into, it only applies to what you are reading from.

5 Likes

Exactly what I was looking for ! Thanks