azriel91

Trait bound on type / result

Feb 25th, 2018
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.94 KB | None | 0 0
  1. /// Loads and returns the data from the specified file.
  2. ///
  3. /// # Parameters:
  4. ///
  5. /// * `conf_dir`: Directory relative to the executable in which to search for configuration.
  6. /// * `file_name`: Name of the file to search for relative to the executable.
  7. /// * `format`: File format.
  8. /// * `additional_base_dirs`: Additional base directories to look into. Useful at development time
  9. ///     when configuration is generated and placed in a separate output directory.
  10. pub fn load_in<T, P>(
  11.     conf_dir: P,
  12.     file_name: &str,
  13.     format: Format,
  14.     additional_base_dirs: Option<Vec<PathBuf>>,
  15. ) -> Result<T>
  16. where
  17.     for<'de> T: Deserialize<'de>,
  18.     P: AsRef<Path> + AsRef<ffi::OsStr>,
  19. {
  20.     let file_path = find_in(conf_dir, file_name, additional_base_dirs)?;
  21.     let file_reader = File::open(file_path)?;
  22.     match format {
  23.         Format::Ron => {
  24.             let result = from_reader(file_reader);
  25.             match result {
  26.                 Ok(data) => Ok(data),
  27.                 Err(ron_de_error) => Err(Error::from_kind(ErrorKind::RonDeserialization(
  28.                     ron_de_error,
  29.                 ))),
  30.             }
  31.         }
  32.     }
  33. }
  34.  
  35. // === Caller === //
  36. fn load_in_returns_error_when_file_does_not_exist() {
  37.     // We don't setup_temp_file(..);
  38.  
  39.     let load_result = load_in::<Result<Data>, _>(
  40.         exe_dir(),
  41.         "test__load_config.ron",
  42.         Format::Ron,
  43.         Some(development_base_dirs!()),
  44.     );
  45.  
  46.     if let &ErrorKind::Find(ref find_context) = load_result.unwrap_err().kind() {
  47.         let mut base_dirs = vec![exe_dir()];
  48.         base_dirs.append(&mut development_base_dirs!());
  49.         let expected = FindContext {
  50.             base_dirs,
  51.             conf_dir: PathBuf::from(""),
  52.             file_name: "test__find_config.ron".to_owned(),
  53.         }; // kcov-ignore
  54.  
  55.         assert_eq!(&expected, find_context);
  56.     } else {
  57.         panic!("Expected `load` to return error"); // kcov-ignore
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment