From cfc746d3a8e6edf7c79f7d12bc788cafcbcca668 Mon Sep 17 00:00:00 2001 From: dignifiedquire Date: Mon, 4 Mar 2024 18:19:16 +0100 Subject: [PATCH] improve examples --- sha1-checked/README.md | 12 +++++++----- sha1-checked/src/lib.rs | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/sha1-checked/README.md b/sha1-checked/README.md index 4cfdf25e..32c4bc91 100644 --- a/sha1-checked/README.md +++ b/sha1-checked/README.md @@ -26,10 +26,11 @@ This implementation will be slower to use than the pure SHA-1 implementation, as ```rust use hex_literal::hex; -use sha1_checked::{Sha1, Digest}; +use sha1_checked::Sha1; -let result = Sha1::digest(b"hello world"); -assert_eq!(result, hex!("2aae6c35c94fcfb415dbe95f408b9ce91ee846ed")); +let result = Sha1::try_digest(b"hello world"); +assert_eq!(result.hash().as_ref(), hex!("2aae6c35c94fcfb415dbe95f408b9ce91ee846ed")); +assert!(!result.has_collision()); ``` ### Incremental API @@ -40,9 +41,10 @@ use sha1_checked::{Sha1, Digest}; let mut hasher = Sha1::new(); hasher.update(b"hello world"); -let hash = hasher.finalize(); +let result = hasher.try_finalize(); -assert_eq!(hash, hex!("2aae6c35c94fcfb415dbe95f408b9ce91ee846ed")); +assert_eq!(result.hash().as_ref(), hex!("2aae6c35c94fcfb415dbe95f408b9ce91ee846ed")); +assert!(!result.has_collision()); ``` Also, see the [examples section] in the RustCrypto/hashes readme. diff --git a/sha1-checked/src/lib.rs b/sha1-checked/src/lib.rs index caab8948..25baf66e 100644 --- a/sha1-checked/src/lib.rs +++ b/sha1-checked/src/lib.rs @@ -79,6 +79,24 @@ impl Sha1 { Builder::default() } + /// Oneshot hashing, reporting the collision state. + /// + /// # Examples + /// + /// ``` + /// use hex_literal::hex; + /// use sha1_checked::Sha1; + /// + /// let result = Sha1::try_digest(b"hello world"); + /// assert_eq!(result.hash().as_ref(), hex!("2aae6c35c94fcfb415dbe95f408b9ce91ee846ed")); + /// assert!(!result.has_collision()); + /// ``` + pub fn try_digest(data: impl AsRef<[u8]>) -> CollisionResult { + let mut hasher = Self::default(); + Digest::update(&mut hasher, data); + hasher.try_finalize() + } + /// Try finalization, reporting the collision state. pub fn try_finalize(mut self) -> CollisionResult { let mut out = Output::::default();