Skip to content

New lint: Give a warning when calling File::bytes, TcpStream::bytes(), etc #14087

Closed
@JonathanBrouwer

Description

@JonathanBrouwer

What it does

There should be a lint that gives a warning when calling File::bytes(), TcpStream::bytes(), and maybe others.
These functions (almost?) should never be called since File and TcpStream are unbuffered and will perform a syscall everytime .next() is called. This is also noted on the docs page of the function.

I'm not sure an automatic fix will be possible, since if the bytes() is used only partially, the file is only read partially. Inserting the bufreader would change this behaviour.

Advantage

  • I measured the rewritten code to be ~1000x faster for large file

Drawbacks

  • Theoretically a user could write file.bytes().next(), then dropping the iterator. In this case, adding the BufReader would make no difference. I expect this to be a rare situation though.

Example

let file = File::open("./bytes.txt").unwrap();
let zero_bytes_count = file.bytes().map(|b| b.unwrap()).filter(|b| *b == 0).count();

Could be written as:

let file = BufReader::new(File::open("./bytes.txt").unwrap());
let zero_bytes_count = file.bytes().map(|b| b.unwrap()).filter(|b| *b == 0).count();

Metadata

Metadata

Labels

A-lintArea: New lints

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions