summaryrefslogtreecommitdiff
path: root/meap/meap-code/ch3/ch3-file-states.rs
blob: 36510a591de4f615914b4b00fb2f5577b4f110ed (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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);
}