From 1680dc7c18135548d1a0e237d5b4a8d95a79cd68 Mon Sep 17 00:00:00 2001 From: Mike Buland Date: Tue, 25 Nov 2025 09:47:08 -0800 Subject: First stab at adding async/tokio support. --- rust/src/lib.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'rust/src/lib.rs') diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 2ccc2cf..6f52702 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -28,6 +28,9 @@ use std::num::FpCategory; use std::sync::LazyLock; use std::vec::Vec; +#[cfg(feature = "tokio")] +use tokio::io::{AsyncReadExt,AsyncWriteExt,AsyncRead,AsyncWrite}; + /// Represents a value in a Gats structure. #[derive(PartialEq)] pub enum Value { @@ -395,6 +398,17 @@ impl Value { Err(e) => Err(e), } } + + #[cfg(feature = "tokio")] + pub async fn write_packet_async(&self, w: &mut W) -> Result<(), Error> + where + W: AsyncWrite + Unpin + { + match self.to_packet() { + Ok(body) => w.write_all(&body).await, + Err(e) => Err(e), + } + } pub fn bytes_to_read(r: &[u8]) -> Result { if r.len() < 5 { @@ -468,6 +482,35 @@ impl Value { } } } + + #[cfg(feature = "tokio")] + pub async fn read_packet_async(r: &mut R) -> Result + where + R: AsyncRead + Unpin + { + let mut buf = Vec::::new(); + let mut fill = 0usize; + loop { + match Value::bytes_to_read(&buf) { + Ok(BytesToRead::Estimate(size)) => { + buf.resize(size, 0u8); + let amount = r.read(&mut buf[fill..]).await?; + fill += amount; + } + Ok(BytesToRead::Final(size)) => { + buf.resize(size, 0u8); + let amount = r.read(&mut buf[fill..]).await?; + fill += amount; + if fill == size { + return Value::from_packet(&buf); + } + } + Err(e) => { + return Err(e); + } + } + } + } } impl From for Value { @@ -649,4 +692,10 @@ mod tests { assert!(v == v2); Ok(()) } + + #[cfg(feature = "tokio")] + #[test] + fn async_test() -> Result<(), Box> { + Ok(()) + } } -- cgit v1.2.3