Skip to content

Commit

Permalink
Separate parsing of options functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
TheQuantumPhysicist committed Oct 4, 2024
1 parent c2e52c2 commit abd0cd6
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
23 changes: 23 additions & 0 deletions src/hasher/options/common.rs
Original file line number Diff line number Diff line change
@@ -1 +1,24 @@
use std::{collections::BTreeMap, str::FromStr};

use anyhow::Context;

pub const OUTPUT_SIZE_KEY: &str = "output-size";

pub fn parse_option<T: FromStr>(
options: &BTreeMap<String, String>,
option_key: impl AsRef<str>,
default_value: T,
) -> anyhow::Result<T>
where
<T as FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
let parsed: T = options
.get(option_key.as_ref())
.cloned()
.map(|s| s.parse())
.transpose()
.context(format!("While parsing option `{}`", option_key.as_ref()))?
.unwrap_or(default_value);

Ok(parsed)
}
15 changes: 6 additions & 9 deletions src/hasher/options/k12_options.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use std::{collections::BTreeMap, num::NonZeroUsize};

use anyhow::Context;

use super::{common::OUTPUT_SIZE_KEY, traits::HashingOptions};
use super::{
common::{parse_option, OUTPUT_SIZE_KEY},
traits::HashingOptions,
};

pub const DEFAULT_OUTPUT_SIZE: NonZeroUsize = match NonZeroUsize::new(32) {
Some(v) => v,
Expand All @@ -17,12 +18,8 @@ impl TryFrom<BTreeMap<String, String>> for K12Options {
type Error = anyhow::Error;

fn try_from(options: BTreeMap<String, String>) -> Result<Self, Self::Error> {
let output_size: NonZeroUsize = options
.get(OUTPUT_SIZE_KEY)
.cloned()
.unwrap_or(DEFAULT_OUTPUT_SIZE.to_string())
.parse()
.context(format!("While parsing option `{OUTPUT_SIZE_KEY}`"))?;
let output_size =
parse_option::<NonZeroUsize>(&options, OUTPUT_SIZE_KEY, DEFAULT_OUTPUT_SIZE)?;

Ok(Self { output_size })
}
Expand Down

0 comments on commit abd0cd6

Please sign in to comment.