aboutsummaryrefslogtreecommitdiff
path: root/rust/src/lib.rs
diff options
context:
space:
mode:
Diffstat (limited to 'rust/src/lib.rs')
-rw-r--r--rust/src/lib.rs49
1 files changed, 49 insertions, 0 deletions
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;
28use std::sync::LazyLock; 28use std::sync::LazyLock;
29use std::vec::Vec; 29use std::vec::Vec;
30 30
31#[cfg(feature = "tokio")]
32use tokio::io::{AsyncReadExt,AsyncWriteExt,AsyncRead,AsyncWrite};
33
31/// Represents a value in a Gats structure. 34/// Represents a value in a Gats structure.
32#[derive(PartialEq)] 35#[derive(PartialEq)]
33pub enum Value { 36pub enum Value {
@@ -395,6 +398,17 @@ impl Value {
395 Err(e) => Err(e), 398 Err(e) => Err(e),
396 } 399 }
397 } 400 }
401
402 #[cfg(feature = "tokio")]
403 pub async fn write_packet_async<W>(&self, w: &mut W) -> Result<(), Error>
404 where
405 W: AsyncWrite + Unpin
406 {
407 match self.to_packet() {
408 Ok(body) => w.write_all(&body).await,
409 Err(e) => Err(e),
410 }
411 }
398 412
399 pub fn bytes_to_read(r: &[u8]) -> Result<BytesToRead, Error> { 413 pub fn bytes_to_read(r: &[u8]) -> Result<BytesToRead, Error> {
400 if r.len() < 5 { 414 if r.len() < 5 {
@@ -468,6 +482,35 @@ impl Value {
468 } 482 }
469 } 483 }
470 } 484 }
485
486 #[cfg(feature = "tokio")]
487 pub async fn read_packet_async<R>(r: &mut R) -> Result<Value, Error>
488 where
489 R: AsyncRead + Unpin
490 {
491 let mut buf = Vec::<u8>::new();
492 let mut fill = 0usize;
493 loop {
494 match Value::bytes_to_read(&buf) {
495 Ok(BytesToRead::Estimate(size)) => {
496 buf.resize(size, 0u8);
497 let amount = r.read(&mut buf[fill..]).await?;
498 fill += amount;
499 }
500 Ok(BytesToRead::Final(size)) => {
501 buf.resize(size, 0u8);
502 let amount = r.read(&mut buf[fill..]).await?;
503 fill += amount;
504 if fill == size {
505 return Value::from_packet(&buf);
506 }
507 }
508 Err(e) => {
509 return Err(e);
510 }
511 }
512 }
513 }
471} 514}
472 515
473impl From<i64> for Value { 516impl From<i64> for Value {
@@ -649,4 +692,10 @@ mod tests {
649 assert!(v == v2); 692 assert!(v == v2);
650 Ok(()) 693 Ok(())
651 } 694 }
695
696 #[cfg(feature = "tokio")]
697 #[test]
698 fn async_test() -> Result<(), Box<dyn Error>> {
699 Ok(())
700 }
652} 701}