Skip to content

Commit fb9e983

Browse files
committed
ch7: add ch7-write123 example
1 parent aff3c02 commit fb9e983

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

ch7/ch7-write123/Cargo.toml

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
[package]
2+
name = "write123"
3+
version = "0.1.0"
4+
authors = ["Tim McNamara <author@rustinaction.com>"]
5+
edition = "2018"
6+
7+
[dependencies]
8+
byteorder = "1.2"

ch7/ch7-write123/src/main.rs

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
use std::io::Cursor;
2+
use byteorder::{LittleEndian};
3+
use byteorder::{ReadBytesExt, WriteBytesExt};
4+
5+
fn write_numbers_to_file() -> (u32, i8, f64) {
6+
let mut w = vec![]; // slices implement Read and Write, and can thus act as mock files
7+
8+
let one: u32 = 1;
9+
let two: i8 = 2;
10+
let three: f64 = 3.0;
11+
12+
w.write_u32::<LittleEndian>(one).unwrap();
13+
println!("{:?}", &w);
14+
15+
w.write_i8(two).unwrap(); // single byte methods don't take an endianness parameter
16+
println!("{:?}", &w);
17+
18+
w.write_f64::<LittleEndian>(three).unwrap();
19+
println!("{:?}", &w);
20+
21+
(one, two, three)
22+
}
23+
24+
fn read_numbers_from_file() -> (u32, i8, f64) {
25+
let mut r = Cursor::new(vec![1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 8, 64]);
26+
let one_ = r.read_u32::<LittleEndian>().unwrap();
27+
let two_ = r.read_i8().unwrap();
28+
let three_ = r.read_f64::<LittleEndian>().unwrap();
29+
30+
(one_, two_, three_)
31+
}
32+
33+
fn main() {
34+
write_numbers_to_file();
35+
read_numbers_from_file();
36+
}

0 commit comments

Comments
 (0)