Debian Codegraph @

examples/file_numbers.rs

raw symbols SCIP
1 use std::env::args;
2
3 use anyhow::Context;
4 use async_fn_stream::try_fn_stream;
5 use futures_util::{pin_mut, Stream, StreamExt};
6 use tokio::{
7 fs::File,
8 io::{AsyncBufReadExt, BufReader},
9 };
10
11 #[tokio::main]
12 async fn main() -> Result<(), anyhow::Error> {
13 let file_name = args().nth(1).unwrap();
14 let stream = read_numbers(file_name);
15 pin_mut!(stream);
16 while let Some(number) = stream.next().await {
17 println!("number: {}", number?);
18 }
19
20 Ok(())
21 }
22
23 fn read_numbers(file_name: String) -> impl Stream<Item = Result<i32, anyhow::Error>> {
24 try_fn_stream(|emitter| async move {
25 let file = BufReader::new(File::open(file_name).await.context("Failed to open file")?);
26 pin_mut!(file);
27 let mut line = String::new();
28 loop {
29 line.clear();
30 let byte_count = file
31 .read_line(&mut line)
32 .await
33 .context("Failed to read line")?;
34 if byte_count == 0 {
35 break;
36 }
37
38 for token in line.split_ascii_whitespace() {
39 let number: i32 = token
40 .parse()
41 .with_context(|| format!("Failed to conver string \"{token}\" to number"))?;
42 emitter.emit(number).await;
43 }
44 }
45
46 Ok(())
47 })
48 }