nix_compat/hashing.rs
1//! Helpers that calcutate the hash of the data written
2//! and count the number of bytes written.
3
4use tokio_util::io::InspectReader;
5
6/// Copies all data from the passed reader to the passed writer.
7/// Afterwards, it also returns the resulting [digest::Digest],
8/// as well as the number of bytes copied.
9/// The exact hash function used is left generic over all [digest::Digest].
10pub async fn hash<D: digest::Digest + std::io::Write>(
11 mut r: impl tokio::io::AsyncRead + Unpin,
12 mut w: impl tokio::io::AsyncWrite + Unpin,
13) -> std::io::Result<(digest::Output<D>, u64)> {
14 let mut hasher = D::new();
15 let bytes_copied = tokio::io::copy(
16 &mut InspectReader::new(&mut r, |d| hasher.write_all(d).unwrap()),
17 &mut w,
18 )
19 .await?;
20 Ok((hasher.finalize(), bytes_copied))
21}