tauri_api/
file.rs

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
mod extract;
mod file_move;

use std::fs;
use std::path::Path;

use crate::Error;

pub use extract::*;
pub use file_move::*;

/// Reads a string file.
pub fn read_string<P: AsRef<Path>>(file: P) -> crate::Result<String> {
  fs::read_to_string(file).map_err(|err| Error::File(format!("Read_string failed: {}", err)).into())
}

/// Reads a binary file.
pub fn read_binary<P: AsRef<Path>>(file: P) -> crate::Result<Vec<u8>> {
  fs::read(file).map_err(|err| Error::File(format!("Read_binary failed: {}", err)).into())
}

#[cfg(test)]
mod test {
  use super::*;
  use crate::Error;

  #[test]
  fn check_read_string() {
    let file = String::from("test/test.txt");

    let res = read_string(file);

    assert!(res.is_ok());

    if let Ok(s) = res {
      assert_eq!(s, "This is a test doc!".to_string());
    }
  }

  #[test]
  fn check_read_string_fail() {
    let file = String::from("test/");

    let res = read_string(file);

    assert!(res.is_err());

    if let Some(Error::File(e)) = res.unwrap_err().downcast_ref::<Error>() {
      #[cfg(windows)]
      assert_eq!(
        *e,
        "Read_string failed: Access is denied. (os error 5)".to_string()
      );
      #[cfg(not(windows))]
      assert_eq!(
        *e,
        "Read_string failed: Is a directory (os error 21)".to_string()
      );
    }
  }

  #[test]
  fn check_read_binary() {
    let file = String::from("test/test_binary");

    #[cfg(windows)]
    let expected_vec = vec![
      35, 33, 47, 98, 105, 110, 47, 98, 97, 115, 104, 13, 10, 13, 10, 101, 99, 104, 111, 32, 34,
      72, 101, 108, 108, 111, 32, 116, 104, 101, 114, 101, 34,
    ];
    #[cfg(not(windows))]
    let expected_vec = vec![
      35, 33, 47, 98, 105, 110, 47, 98, 97, 115, 104, 10, 10, 101, 99, 104, 111, 32, 34, 72, 101,
      108, 108, 111, 32, 116, 104, 101, 114, 101, 34,
    ];

    let res = read_binary(file);

    assert!(res.is_ok());

    if let Ok(vec) = res {
      assert_eq!(vec, expected_vec);
    }
  }

  #[test]
  fn check_read_binary_fail() {
    let file = String::from("test/");

    let res = read_binary(file);

    assert!(res.is_err());

    if let Some(Error::File(e)) = res.unwrap_err().downcast_ref::<Error>() {
      #[cfg(windows)]
      assert_eq!(
        *e,
        "Read_binary failed: Access is denied. (os error 5)".to_string()
      );
      #[cfg(not(windows))]
      assert_eq!(
        *e,
        "Read_binary failed: Is a directory (os error 21)".to_string()
      );
    }
  }
}