minigrep/
runtime.rs

1use super::Config;
2use super::USAGE;
3
4/// Runtime variables and resources are held here
5/// including but not limited to config.
6pub struct Runtime {
7  config: Config,
8}
9
10impl Runtime {
11  /// Create a runtime from a config instance
12  pub fn new(config: Config) -> Self { Self { config } }
13
14  /// Run the application, if an error occurs,
15  /// return it to the caller for handling.
16  pub fn try_run(&self) -> Result<(), std::io::Error> {
17    let text = std::fs::read_to_string(&self.config.file_path)?;
18    crate::core::show_found(&self.config, text.lines());
19    Ok(())
20  }
21  /// Run the application and `panic!()` if an error occurs.
22  /// # Panics
23  /// - If `Config::file_path` is not read successfully.
24  pub fn run(&self) {
25    self.try_run().unwrap_or_else(|err| {
26      eprintln!("{USAGE}\n\nRunning program failed: {err}");
27      std::process::exit(2);
28    })
29  }
30}