From 04382608ba3b82928d4b64a8453a408f612563ed Mon Sep 17 00:00:00 2001 From: lightsing Date: Sun, 17 Sep 2023 19:44:22 +0800 Subject: [PATCH] impl AsyncWrite for Hasher --- Cargo.toml | 4 ++++ src/lib.rs | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index d92fc6e55..3a781c962 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -87,6 +87,9 @@ no_avx2 = [] no_avx512 = [] no_neon = [] +# This feature enables the tokio AsyncWrite implementation for the hashers. +tokio = ["dep:tokio", "std"] + [package.metadata.docs.rs] # Document the rayon/mmap methods and the Zeroize impls on docs.rs. features = ["mmap", "rayon", "zeroize"] @@ -100,6 +103,7 @@ cfg-if = "1.0.0" digest = { version = "0.10.1", features = [ "mac" ], optional = true } zeroize = { version = "1", default-features = false, features = ["zeroize_derive"], optional = true } memmap2 = { version = "0.7.1", optional = true } +tokio = { version = "1", default-features = false, features = [], optional = true } [dev-dependencies] hmac = "0.12.0" diff --git a/src/lib.rs b/src/lib.rs index 5b03ff9f7..61207d608 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1516,6 +1516,44 @@ impl std::io::Write for Hasher { } } +#[cfg(feature = "tokio")] +impl tokio::io::AsyncWrite for Hasher { + fn poll_write( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + buf: &[u8], + ) -> std::task::Poll> { + self.get_mut().update(buf); + std::task::Poll::Ready(Ok(buf.len())) + } + + fn poll_flush( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + + fn poll_shutdown( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + + fn poll_write_vectored( + mut self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + bufs: &[std::io::IoSlice<'_>], + ) -> std::task::Poll> { + std::task::Poll::Ready(std::io::Write::write_vectored(&mut *self, bufs)) + } + + fn is_write_vectored(&self) -> bool { + true + } +} + /// An incremental reader for extended output, returned by /// [`Hasher::finalize_xof`](struct.Hasher.html#method.finalize_xof). ///