Skip to content

Commit 3f5218e

Browse files
authored
Merge pull request #17 from laysakura/section-3_1
3.1: `std::io::Read` を実装した何かから最大1024bytes読み込んで HEX 表示するプログラム
2 parents 372d113 + 73e1658 commit 3f5218e

File tree

4 files changed

+44
-3
lines changed

4 files changed

+44
-3
lines changed

chapter3/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,7 @@ edition = "2018"
77
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
88

99
[dependencies]
10+
11+
[[bin]]
12+
name = "main_3_1"
13+
path = "src/3_1/main.rs"

chapter3/src/3_1/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/3_1/main.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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(())
21+
}

chapter3/src/main.rs

Lines changed: 0 additions & 3 deletions
This file was deleted.

0 commit comments

Comments
 (0)