Coverage Report

Created: 2026-07-16 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/digest-0.11.3/src/lib.rs
Line
Count
Source
1
#![no_std]
2
#![cfg_attr(docsrs, feature(doc_cfg))]
3
#![doc = include_str!("../README.md")]
4
#![forbid(unsafe_code)]
5
#![doc(
6
    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
7
    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
8
)]
9
#![allow(clippy::unwrap_used)] // TODO
10
11
//! ## Structure
12
//!
13
//! Traits in this crate are organized into the following levels:
14
//!
15
//! - **High-level convenience traits**: [`Digest`], [`DynDigest`], [`Mac`].
16
//!   Wrappers around lower-level traits for most common use-cases. Users should
17
//!   usually prefer using these traits.
18
//! - **Mid-level traits**: [`Update`], [`FixedOutput`], [`FixedOutputReset`], [`ExtendableOutput`],
19
//!   [`ExtendableOutputReset`], [`XofReader`], [`Reset`], [`KeyInit`], and [`InnerInit`].
20
//!   These traits atomically describe available functionality of an algorithm.
21
//! - **Marker traits**: [`HashMarker`], [`MacMarker`]. Used to distinguish
22
//!   different algorithm classes.
23
//! - **Low-level traits** defined in the [`block_api`] module. These traits
24
//!   operate at a block-level and do not contain any built-in buffering.
25
//!   They are intended to be implemented by low-level algorithm providers only.
26
//!   Usually they should not be used in application-level code.
27
//!
28
//! Additionally hash functions implement traits from the standard library:
29
//! [`Default`] and [`Clone`].
30
//!
31
//! This crate does not provide any implementations of the `io::Read/Write` traits,
32
//! see the [`digest-io`] crate for `std::io`-compatibility wrappers.
33
//!
34
//! [`digest-io`]: https://docs.rs/digest-io
35
36
#[cfg(feature = "alloc")]
37
#[macro_use]
38
extern crate alloc;
39
40
#[cfg(feature = "rand_core")]
41
pub use common::rand_core;
42
43
#[cfg(feature = "zeroize")]
44
pub use zeroize;
45
46
#[cfg(feature = "alloc")]
47
use alloc::boxed::Box;
48
49
#[cfg(feature = "dev")]
50
pub mod dev;
51
52
#[cfg(feature = "block-api")]
53
pub mod block_api;
54
mod buffer_macros;
55
mod digest;
56
#[cfg(feature = "mac")]
57
mod mac;
58
mod xof_fixed;
59
60
#[cfg(feature = "block-api")]
61
pub use block_buffer;
62
pub use common;
63
#[cfg(feature = "oid")]
64
pub use const_oid;
65
66
#[cfg(feature = "oid")]
67
pub use crate::digest::DynDigestWithOid;
68
pub use crate::digest::{Digest, DynDigest, HashMarker};
69
#[cfg(feature = "mac")]
70
pub use common::{InnerInit, InvalidLength, Key, KeyInit};
71
pub use common::{Output, OutputSizeUser, Reset, array, typenum, typenum::consts};
72
#[cfg(feature = "mac")]
73
pub use mac::{CtOutput, Mac, MacError, MacMarker};
74
pub use xof_fixed::XofFixedWrapper;
75
76
use common::typenum::Unsigned;
77
use core::fmt;
78
79
/// Types which consume data with byte granularity.
80
pub trait Update {
81
    /// Update state using the provided data.
82
    fn update(&mut self, data: &[u8]);
83
84
    /// Digest input data in a chained manner.
85
    #[must_use]
86
    fn chain(mut self, data: impl AsRef<[u8]>) -> Self
87
    where
88
        Self: Sized,
89
    {
90
        self.update(data.as_ref());
91
        self
92
    }
93
}
94
95
/// Trait for hash functions with fixed-size output.
96
pub trait FixedOutput: Update + OutputSizeUser + Sized {
97
    /// Consume value and write result into provided array.
98
    fn finalize_into(self, out: &mut Output<Self>);
99
100
    /// Retrieve result and consume the hasher instance.
101
    #[inline]
102
0
    fn finalize_fixed(self) -> Output<Self> {
103
0
        let mut out = Default::default();
104
0
        self.finalize_into(&mut out);
105
0
        out
106
0
    }
107
}
108
109
/// Trait for hash functions with fixed-size output able to reset themselves.
110
pub trait FixedOutputReset: FixedOutput + Reset {
111
    /// Write result into provided array and reset the hasher state.
112
    fn finalize_into_reset(&mut self, out: &mut Output<Self>);
113
114
    /// Retrieve result and reset the hasher state.
115
    #[inline]
116
    fn finalize_fixed_reset(&mut self) -> Output<Self> {
117
        let mut out = Default::default();
118
        self.finalize_into_reset(&mut out);
119
        out
120
    }
121
}
122
123
/// Trait for reader types which are used to extract extendable output
124
/// from a XOF (extendable-output function) result.
125
pub trait XofReader {
126
    /// Read output into the `buffer`. Can be called an unlimited number of times.
127
    fn read(&mut self, buffer: &mut [u8]);
128
129
    /// Read output into a boxed slice of the specified size.
130
    ///
131
    /// Can be called an unlimited number of times in combination with `read`.
132
    ///
133
    /// `Box<[u8]>` is used instead of `Vec<u8>` to save stack space, since
134
    /// they have size of 2 and 3 words respectively.
135
    #[cfg(feature = "alloc")]
136
    fn read_boxed(&mut self, n: usize) -> Box<[u8]> {
137
        let mut buf = vec![0u8; n].into_boxed_slice();
138
        self.read(&mut buf);
139
        buf
140
    }
141
}
142
143
/// Trait for hash functions with extendable-output (XOF).
144
pub trait ExtendableOutput: Sized + Update {
145
    /// Reader
146
    type Reader: XofReader;
147
148
    /// Retrieve XOF reader and consume hasher instance.
149
    fn finalize_xof(self) -> Self::Reader;
150
151
    /// Finalize XOF and write result into `out`.
152
    fn finalize_xof_into(self, out: &mut [u8]) {
153
        self.finalize_xof().read(out);
154
    }
155
156
    /// Compute hash of `data` and write it into `output`.
157
    fn digest_xof(input: impl AsRef<[u8]>, output: &mut [u8])
158
    where
159
        Self: Default,
160
    {
161
        let mut hasher = Self::default();
162
        hasher.update(input.as_ref());
163
        hasher.finalize_xof().read(output);
164
    }
165
166
    /// Retrieve result into a boxed slice of the specified size and consume
167
    /// the hasher.
168
    ///
169
    /// `Box<[u8]>` is used instead of `Vec<u8>` to save stack space, since
170
    /// they have size of 2 and 3 words respectively.
171
    #[cfg(feature = "alloc")]
172
    fn finalize_boxed(self, output_size: usize) -> Box<[u8]> {
173
        let mut buf = vec![0u8; output_size].into_boxed_slice();
174
        self.finalize_xof().read(&mut buf);
175
        buf
176
    }
177
}
178
179
/// Trait for hash functions with extendable-output (XOF) able to reset themselves.
180
pub trait ExtendableOutputReset: ExtendableOutput + Reset {
181
    /// Retrieve XOF reader and reset hasher instance state.
182
    fn finalize_xof_reset(&mut self) -> Self::Reader;
183
184
    /// Finalize XOF, write result into `out`, and reset the hasher state.
185
    fn finalize_xof_reset_into(&mut self, out: &mut [u8]) {
186
        self.finalize_xof_reset().read(out);
187
    }
188
189
    /// Retrieve result into a boxed slice of the specified size and reset
190
    /// the hasher state.
191
    ///
192
    /// `Box<[u8]>` is used instead of `Vec<u8>` to save stack space, since
193
    /// they have size of 2 and 3 words respectively.
194
    #[cfg(feature = "alloc")]
195
    fn finalize_boxed_reset(&mut self, output_size: usize) -> Box<[u8]> {
196
        let mut buf = vec![0u8; output_size].into_boxed_slice();
197
        self.finalize_xof_reset().read(&mut buf);
198
        buf
199
    }
200
}
201
202
/// Trait for hash functions with customization string for domain separation.
203
pub trait CustomizedInit: Sized {
204
    /// Create new hasher instance with the given customization string.
205
    fn new_customized(customization: &[u8]) -> Self;
206
}
207
208
/// Trait for hash functions with customization string for domain separation which place
209
/// restrictions on customization strings.
210
pub trait TryCustomizedInit: Sized {
211
    /// Error returned for invalid customization strings.
212
    type Error;
213
214
    /// Create new hasher instance with the given customization string.
215
    ///
216
    /// # Errors
217
    /// If the provided customization string is not valid for the hash function.
218
    fn try_new_customized(customization: &[u8]) -> Result<Self, Self::Error>;
219
}
220
221
impl<T: CustomizedInit> TryCustomizedInit for T {
222
    type Error = core::convert::Infallible;
223
224
    fn try_new_customized(customization: &[u8]) -> Result<Self, Self::Error> {
225
        Ok(Self::new_customized(customization))
226
    }
227
}
228
229
/// Types with a certain collision resistance.
230
pub trait CollisionResistance {
231
    /// Collision resistance in bytes.
232
    ///
233
    /// This applies to an output size of at least `2 * CollisionResistance` bytes.
234
    /// For a smaller output size collision resistance can be usually calculated as
235
    /// `min(CollisionResistance, OutputSize / 2)`.
236
    type CollisionResistance: Unsigned;
237
}
238
239
/// The error type used in variable hash traits.
240
#[derive(Clone, Copy, Debug, Default)]
241
pub struct InvalidOutputSize;
242
243
impl fmt::Display for InvalidOutputSize {
244
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245
        f.write_str("invalid output size")
246
    }
247
}
248
249
impl core::error::Error for InvalidOutputSize {}
250
251
/// Buffer length is not equal to hash output size.
252
#[derive(Default, Debug, Copy, Clone, Eq, PartialEq)]
253
pub struct InvalidBufferSize;
254
255
impl fmt::Display for InvalidBufferSize {
256
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257
        f.write_str("invalid buffer length")
258
    }
259
}
260
261
impl core::error::Error for InvalidBufferSize {}