Skip to main content

irust_repl/
executor.rs

1#[cfg(feature = "serde")]
2use serde::{Deserialize, Serialize};
3use std::str::FromStr;
4
5#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6#[derive(Debug, Clone, Copy, Default)]
7pub enum Executor {
8    #[default]
9    Sync,
10    Tokio,
11    AsyncStd,
12}
13
14impl Executor {
15    pub(crate) fn main(&self) -> String {
16        match self {
17            Executor::Sync => "fn main()".into(),
18            Executor::Tokio => "#[tokio::main]async fn main()".into(),
19            Executor::AsyncStd => "#[async_std::main]async fn main()".into(),
20        }
21    }
22    /// Invokation that can be used with cargo-add
23    /// The first argument is the crate name, it should be used with cargo-rm
24    pub(crate) fn dependecy(&self) -> Option<Vec<String>> {
25        match self {
26            Executor::Sync => None,
27            Executor::Tokio => Some(vec![
28                "tokio".into(),
29                "--features".into(),
30                "macros rt-multi-thread".into(),
31            ]),
32            Executor::AsyncStd => Some(vec![
33                "async_std".into(),
34                "--features".into(),
35                "attributes".into(),
36            ]),
37        }
38    }
39}
40impl FromStr for Executor {
41    type Err = Box<dyn std::error::Error>;
42    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
43        match s {
44            "sync" => Ok(Executor::Sync),
45            "tokio" => Ok(Executor::Tokio),
46            "async_std" => Ok(Executor::AsyncStd),
47            _ => Err("Unknown executor".into()),
48        }
49    }
50}
51
52impl std::fmt::Display for Executor {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        match self {
55            Executor::Sync => write!(f, "sync"),
56            Executor::Tokio => write!(f, "tokio"),
57            Executor::AsyncStd => write!(f, "async_std"),
58        }
59    }
60}