From 7e8ee5ed9cad6484e9f13f81731b102ced58402e Mon Sep 17 00:00:00 2001 From: Adam Carpenter Date: Tue, 9 Jul 2019 15:14:04 -0400 Subject: Init. --- meap/meap-code/ch3/fileresult/Cargo.toml | 7 ++++ meap/meap-code/ch3/fileresult/src/main.rs | 65 +++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100755 meap/meap-code/ch3/fileresult/Cargo.toml create mode 100755 meap/meap-code/ch3/fileresult/src/main.rs (limited to 'meap/meap-code/ch3/fileresult') diff --git a/meap/meap-code/ch3/fileresult/Cargo.toml b/meap/meap-code/ch3/fileresult/Cargo.toml new file mode 100755 index 0000000..d5902d0 --- /dev/null +++ b/meap/meap-code/ch3/fileresult/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "fileresult" +version = "0.1.0" +authors = ["Tim McNamara "] + +[dependencies] +rand = "0.3" \ No newline at end of file diff --git a/meap/meap-code/ch3/fileresult/src/main.rs b/meap/meap-code/ch3/fileresult/src/main.rs new file mode 100755 index 0000000..c02d959 --- /dev/null +++ b/meap/meap-code/ch3/fileresult/src/main.rs @@ -0,0 +1,65 @@ +extern crate rand; // <1> +use rand::Rng; // <2> + +fn one_in(n: u32) -> bool { // <3> + rand::thread_rng().gen_weighted_bool(n) +} + +#[derive(Debug)] +struct File { + name: String, + data: Vec, +} + +impl File { + fn new(name: &str) -> File { + File { name: String::from(name), data: Vec::new() } // <4> + } + + fn new_with_data(name: &str, data: &Vec) -> File { + let mut f = File::new(name); + f.data = data.clone(); + f + } + + fn read(self: &File, save_to: &mut Vec) -> Result { // <5> + let mut tmp = self.data.clone(); + let read_length = tmp.len(); + save_to.reserve(read_length); + save_to.append(&mut tmp); + Ok(read_length) // <6> + } +} + +fn open(f: File) -> Result { + if one_in(10_000) { // <7> + let err_msg = String::from("Permission denied"); + return Err(err_msg); + } + Ok(f) +} + +fn close(f: File) -> Result { + if one_in(100_000) { // <8> + let err_msg = String::from("Interrupted by signal!"); + return Err(err_msg); + } + Ok(f) +} + +fn main() { + let f4_data: Vec = vec![114, 117, 115, 116, 33]; + let mut f4 = File::new_with_data("4.txt", &f4_data); + + let mut buffer: Vec = vec![]; + + f4 = open(f4).unwrap(); // <9> + let f4_length = f4.read(&mut buffer).unwrap(); // <9> + f4 = close(f4).unwrap(); // <9> + + let text = String::from_utf8_lossy(&buffer); + + println!("{:?}", f4); + println!("{} is {} bytes long", &f4.name, f4_length); + println!("{}", text); +} \ No newline at end of file -- cgit v1.2.3