From 68d3e5f4e1bcfe28f92fac0fd66e5308cc493afa Mon Sep 17 00:00:00 2001 From: Daniel Hofstetter Date: Mon, 15 Sep 2025 17:20:45 +0200 Subject: [PATCH] uucore/checksum: improve API of create_sha3() expect usize instead of Option as param --- src/uu/hashsum/src/hashsum.rs | 6 ++++-- src/uucore/src/lib/features/checksum.rs | 24 ++++++++++++------------ 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/uu/hashsum/src/hashsum.rs b/src/uu/hashsum/src/hashsum.rs index 4bdb1fe38..ce9002918 100644 --- a/src/uu/hashsum/src/hashsum.rs +++ b/src/uu/hashsum/src/hashsum.rs @@ -97,8 +97,10 @@ fn create_algorithm_from_flags(matches: &ArgMatches) -> UResult { set_or_err(detect_algo("b3sum", None)?)?; } if matches.get_flag("sha3") { - let bits = matches.get_one::("bits").copied(); - set_or_err(create_sha3(bits)?)?; + match matches.get_one::("bits") { + Some(bits) => set_or_err(create_sha3(*bits)?)?, + None => return Err(ChecksumError::BitsRequiredForSha3.into()), + } } if matches.get_flag("sha3-224") { set_or_err(HashAlgorithm { diff --git a/src/uucore/src/lib/features/checksum.rs b/src/uucore/src/lib/features/checksum.rs index 61df044f3..f4d03b091 100644 --- a/src/uucore/src/lib/features/checksum.rs +++ b/src/uucore/src/lib/features/checksum.rs @@ -249,34 +249,32 @@ impl UError for ChecksumError { /// /// # Returns /// -/// Returns a UResult of a tuple containing the algorithm name, the hasher instance, and -/// the output length in bits or an Err if an unsupported output size is provided, or if -/// the `--bits` flag is missing. -pub fn create_sha3(bits: Option) -> UResult { +/// Returns a `UResult` with an `HashAlgorithm` or an `Err` if an unsupported +/// output size is provided. +pub fn create_sha3(bits: usize) -> UResult { match bits { - Some(224) => Ok(HashAlgorithm { + 224 => Ok(HashAlgorithm { name: "SHA3_224", create_fn: Box::new(|| Box::new(Sha3_224::new())), bits: 224, }), - Some(256) => Ok(HashAlgorithm { + 256 => Ok(HashAlgorithm { name: "SHA3_256", create_fn: Box::new(|| Box::new(Sha3_256::new())), bits: 256, }), - Some(384) => Ok(HashAlgorithm { + 384 => Ok(HashAlgorithm { name: "SHA3_384", create_fn: Box::new(|| Box::new(Sha3_384::new())), bits: 384, }), - Some(512) => Ok(HashAlgorithm { + 512 => Ok(HashAlgorithm { name: "SHA3_512", create_fn: Box::new(|| Box::new(Sha3_512::new())), bits: 512, }), - Some(_) => Err(ChecksumError::InvalidOutputSizeForSha3.into()), - None => Err(ChecksumError::BitsRequiredForSha3.into()), + _ => Err(ChecksumError::InvalidOutputSizeForSha3.into()), } } @@ -459,8 +457,10 @@ pub fn detect_algo(algo: &str, length: Option) -> UResult bits, }) } - //ALGORITHM_OPTIONS_SHA3 | "sha3" => ( - _ if algo.starts_with("sha3") => create_sha3(length), + _ if algo.starts_with("sha3") => { + let bits = length.ok_or(ChecksumError::BitsRequiredForSha3)?; + create_sha3(bits) + } _ => Err(ChecksumError::UnknownAlgorithm.into()), }