irust_repl/
main_result.rs

1use std::{fmt::Display, str::FromStr};
2
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5
6#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7#[derive(Debug, Clone, Copy, Default)]
8pub enum MainResult {
9    /// fn main() -> () {()}
10    #[default]
11    Unit,
12    /// fn main() -> Result<(), Box<dyn std::error::Error>> {Ok(())}
13    /// allows using `?` with no boilerplate
14    Result,
15}
16
17impl MainResult {
18    pub(crate) fn ttype(&self) -> &'static str {
19        match self {
20            Self::Unit => "()",
21            Self::Result => "Result<(), Box<dyn std::error::Error>>",
22        }
23    }
24    pub(crate) fn instance(&self) -> &'static str {
25        match self {
26            Self::Unit => "()",
27            Self::Result => "Ok(())",
28        }
29    }
30}
31
32impl FromStr for MainResult {
33    type Err = Box<dyn std::error::Error>;
34    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
35        match s.to_lowercase().as_str() {
36            "unit" => Ok(MainResult::Unit),
37            "result" => Ok(MainResult::Result),
38            _ => Err("Unknown main result type".into()),
39        }
40    }
41}
42
43impl Display for MainResult {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        match self {
46            MainResult::Unit => write!(f, "Unit"),
47            MainResult::Result => write!(f, "Result<(), Box<dyn std::error::Error>>"),
48        }
49    }
50}