diff options
author | Adam Carpenter <53hornet@gmail.com> | 2019-03-27 15:32:37 -0400 |
---|---|---|
committer | Adam Carpenter <53hornet@gmail.com> | 2019-03-27 15:32:37 -0400 |
commit | 67cdcc2e12118becb823e20a40cc2687f2b8425a (patch) | |
tree | ed92c3234b89079e6d4cf36f5e80c5ffa79def48 /meap/meap-code/ch3/ch3-file-states.rs | |
parent | e25482fca375d318a39c3b54db396b0db6e0b263 (diff) | |
download | learning-rust-67cdcc2e12118becb823e20a40cc2687f2b8425a.tar.xz learning-rust-67cdcc2e12118becb823e20a40cc2687f2b8425a.zip |
Started Rust in Action MEAP.
Diffstat (limited to 'meap/meap-code/ch3/ch3-file-states.rs')
-rw-r--r-- | meap/meap-code/ch3/ch3-file-states.rs | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/meap/meap-code/ch3/ch3-file-states.rs b/meap/meap-code/ch3/ch3-file-states.rs new file mode 100644 index 0000000..36510a5 --- /dev/null +++ b/meap/meap-code/ch3/ch3-file-states.rs @@ -0,0 +1,59 @@ +#[derive(Debug,PartialEq)]
+enum FileState {
+ Open,
+ Closed,
+}
+
+#[derive(Debug)]
+struct File {
+ name: String,
+ data: Vec<u8>,
+ state: FileState,
+}
+
+impl File {
+ fn new(name: &str) -> File {
+ File { name: String::from(name), data: Vec::new(), state: FileState::Closed }
+ }
+
+ fn read(self: &File, save_to: &mut Vec<u8>) -> Result<usize, String> {
+ if self.state != FileState::Open {
+ return Err(String::from("File must be open for reading"));
+ }
+ 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(mut f: File) -> Result<File, String> {
+ f.state = FileState::Open;
+ Ok(f)
+}
+
+fn close(mut f: File) -> Result<File, String> {
+ f.state = FileState::Closed;
+ Ok(f)
+}
+
+fn main() {
+ let mut f5 = File::new("5.txt");
+
+ let mut buffer: Vec<u8> = vec![];
+
+ if f5.read(&mut buffer).is_err() {
+ println!("Error checking is working");
+ }
+
+ f5 = open(f5).unwrap(); // <9>
+ let f5_length = f5.read(&mut buffer).unwrap(); // <9>
+ f5 = close(f5).unwrap(); // <9>
+
+ let text = String::from_utf8_lossy(&buffer);
+
+ println!("{:?}", f5);
+ println!("{} is {} bytes long", &f5.name, f5_length);
+ println!("{}", text);
+}
\ No newline at end of file |