From 4588ccd0408f0c8deca33e6a321295ecc918b195 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Tue, 31 Jan 2023 09:58:09 +0100 Subject: [PATCH] Better use of From/Tryfrom within the blueprint module. --- crates/aiken-project/src/blueprint/mod.rs | 6 ++--- .../aiken-project/src/blueprint/validator.rs | 22 ++++++++++++------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/crates/aiken-project/src/blueprint/mod.rs b/crates/aiken-project/src/blueprint/mod.rs index 1557edab..29f7329f 100644 --- a/crates/aiken-project/src/blueprint/mod.rs +++ b/crates/aiken-project/src/blueprint/mod.rs @@ -30,7 +30,7 @@ impl Blueprint { modules: &CheckedModules, generator: &mut CodeGenerator, ) -> Result { - let preamble = Preamble::from_config(config); + let preamble = config.into(); let validators: Result, Error> = modules .validators() @@ -53,8 +53,8 @@ impl Display for Blueprint { } } -impl Preamble { - pub fn from_config(config: &Config) -> Self { +impl From<&Config> for Preamble { + fn from(config: &Config) -> Self { Preamble { title: config.name.to_string(), description: if config.description.is_empty() { diff --git a/crates/aiken-project/src/blueprint/validator.rs b/crates/aiken-project/src/blueprint/validator.rs index 73e825e3..4d17aa50 100644 --- a/crates/aiken-project/src/blueprint/validator.rs +++ b/crates/aiken-project/src/blueprint/validator.rs @@ -78,7 +78,11 @@ impl Validator { validator: &CheckedModule, def: &TypedFunction, ) -> Result { - let purpose: Purpose = def.name.clone().into(); + let purpose: Purpose = def + .name + .clone() + .try_into() + .expect("unexpected validator name"); assert_return_bool(validator, def)?; assert_min_arity(validator, def, purpose.min_arity())?; @@ -141,14 +145,16 @@ impl Display for Purpose { } } -impl From for Purpose { - fn from(purpose: String) -> Purpose { +impl TryFrom for Purpose { + type Error = String; + + fn try_from(purpose: String) -> Result { match &purpose[..] { - "spend" => Purpose::Spend, - "mint" => Purpose::Mint, - "withdraw" => Purpose::Withdraw, - "publish" => Purpose::Publish, - unexpected => panic!("Can't turn '{}' into any Purpose", unexpected), + "spend" => Ok(Purpose::Spend), + "mint" => Ok(Purpose::Mint), + "withdraw" => Ok(Purpose::Withdraw), + "publish" => Ok(Purpose::Publish), + unexpected => Err(format!("Can't turn '{}' into any Purpose", unexpected)), } } }