Skip to content

Commit 2d88173

Browse files
committed
Merge branch 'section-3_1' of github.com:laysakura/learning-systems-programming-in-rust into section-3_1
2 parents d6be757 + 836c596 commit 2d88173

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

chapter3/src/bytes_read.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
use std::fmt::Display;
2+
3+
#[derive(Debug)]
4+
pub(super) struct BytesRead {
5+
bytes: Vec<u8>,
6+
len: usize,
7+
}
8+
9+
impl BytesRead {
10+
pub(super) fn new(bytes: Vec<u8>, len: usize) -> Self {
11+
Self { bytes, len }
12+
}
13+
}
14+
15+
impl Display for BytesRead {
16+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17+
write!(f, "{} bytes read:\n{:02x?}", self.len, self.bytes)
18+
}
19+
}

chapter3/src/main.rs

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,21 @@
1-
fn main() {
2-
println!("Hello, world!");
1+
mod bytes_read;
2+
3+
use std::{fs::File, io};
4+
5+
use bytes_read::BytesRead;
6+
7+
/// Reads up to 1024 bytes from `r`.
8+
fn read_1024bytes<R: io::Read>(r: &mut R) -> io::Result<BytesRead> {
9+
let mut buf = [0u8; 1024];
10+
let len = r.read(&mut buf)?;
11+
Ok(BytesRead::new(buf.into(), len))
12+
}
13+
14+
fn main() -> io::Result<()> {
15+
let mut f = File::open("Cargo.toml")?;
16+
17+
let bytes_read = read_1024bytes(&mut f)?;
18+
println!("{}", bytes_read);
19+
20+
Ok(())
321
}

0 commit comments

Comments
 (0)