I tried to use this crate, but struggled a lot because I couldn't get my code to work:
martin.mein-iserv.de ~/git/rust/bufreader (master) # cat src/main.rs
use std::fs::File;
use std::io::BufReader;
use std::io::Error;
use std::io::BufRead;
use voncount::ReadCounter;
use voncount::Counter;
fn main() -> Result<(), Error>{
let fh = File::open("test.txt")?;
let readcounter = ReadCounter::from(fh);
let reader = BufReader::new(readcounter);
for line in reader.lines()
{
println!("line: {:?}", line);
}
println!("read bytes: {}", readcounter.count());
Ok(())
}
martin.mein-iserv.de ~/git/rust/bufreader (master) # cargo run
Compiling bufreader v0.1.0 (/root/git/rust/bufreader)
error[E0277]: the trait bound `ReadCounter<'_, _>: From<File>` is not satisfied
--> src/main.rs:10:23
|
10 | let readcounter = ReadCounter::from(fh);
| ^^^^^^^^^^^ the trait `From<File>` is not implemented for `ReadCounter<'_, _>`
|
= help: the trait `From<&mut _>` is implemented for `ReadCounter<'_, _>`
= help: for that trait implementation, expected `&mut _`, found `File`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `bufreader` (bin "bufreader") due to 1 previous error
After a while, I finally figured it out - I need to pass mutable references to ReadCounter and BufReader:
martin.mein-iserv.de ~/git/rust/bufreader (master) # cat src/main.rs
use std::fs::File;
use std::io::BufReader;
use std::io::Error;
use std::io::BufRead;
use voncount::ReadCounter;
use voncount::Counter;
fn main() -> Result<(), Error>{
let mut fh = File::open("test.txt")?;
let mut readcounter = ReadCounter::from(&mut fh);
let reader = BufReader::new(&mut readcounter);
for line in reader.lines()
{
println!("line: {:?}", line);
}
println!("read bytes: {}", readcounter.count());
Ok(())
}
martin.mein-iserv.de ~/git/rust/bufreader (master) # cargo run
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/bufreader`
line: Ok("hello")
line: Ok("world")
read bytes: 12
This example might be helpful to others, so I'm posting it here.