Better use of From/Tryfrom within the blueprint module.

This commit is contained in:
KtorZ 2023-01-31 09:58:09 +01:00
parent 22a1c1dfb4
commit 4588ccd040
No known key found for this signature in database
GPG Key ID: 33173CB6F77F4277
2 changed files with 17 additions and 11 deletions

View File

@ -30,7 +30,7 @@ impl Blueprint {
modules: &CheckedModules, modules: &CheckedModules,
generator: &mut CodeGenerator, generator: &mut CodeGenerator,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
let preamble = Preamble::from_config(config); let preamble = config.into();
let validators: Result<Vec<_>, Error> = modules let validators: Result<Vec<_>, Error> = modules
.validators() .validators()
@ -53,8 +53,8 @@ impl Display for Blueprint {
} }
} }
impl Preamble { impl From<&Config> for Preamble {
pub fn from_config(config: &Config) -> Self { fn from(config: &Config) -> Self {
Preamble { Preamble {
title: config.name.to_string(), title: config.name.to_string(),
description: if config.description.is_empty() { description: if config.description.is_empty() {

View File

@ -78,7 +78,11 @@ impl Validator {
validator: &CheckedModule, validator: &CheckedModule,
def: &TypedFunction, def: &TypedFunction,
) -> Result<Validator, Error> { ) -> Result<Validator, Error> {
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_return_bool(validator, def)?;
assert_min_arity(validator, def, purpose.min_arity())?; assert_min_arity(validator, def, purpose.min_arity())?;
@ -141,14 +145,16 @@ impl Display for Purpose {
} }
} }
impl From<String> for Purpose { impl TryFrom<String> for Purpose {
fn from(purpose: String) -> Purpose { type Error = String;
fn try_from(purpose: String) -> Result<Purpose, Self::Error> {
match &purpose[..] { match &purpose[..] {
"spend" => Purpose::Spend, "spend" => Ok(Purpose::Spend),
"mint" => Purpose::Mint, "mint" => Ok(Purpose::Mint),
"withdraw" => Purpose::Withdraw, "withdraw" => Ok(Purpose::Withdraw),
"publish" => Purpose::Publish, "publish" => Ok(Purpose::Publish),
unexpected => panic!("Can't turn '{}' into any Purpose", unexpected), unexpected => Err(format!("Can't turn '{}' into any Purpose", unexpected)),
} }
} }
} }