wrpc_pack/
lib.rs

1//! Stopgap solution for packing and unpacking wRPC values to/from singular, flat byte buffers.
2//!
3//! All APIs in this crate are to be considered unstable and everything may break arbitrarily.
4//!
5//! This crate will never reach 1.0 and will be deprecated once <https://github.com/bytecodealliance/wrpc/issues/25> is complete
6//!
7//! This crate is maintained on a best-effort basis.
8
9use core::pin::Pin;
10use core::task::{Context, Poll};
11
12use bytes::BytesMut;
13use tokio::io::{AsyncRead, AsyncWrite};
14use tokio_util::codec::{Decoder, Encoder};
15use wrpc_transport::{Decode, Deferred as _, Encode};
16
17/// A stream, which fails on each operation, this type should only ever be used in trait bounds
18pub struct NoopStream;
19
20impl AsyncRead for NoopStream {
21    fn poll_read(
22        self: Pin<&mut Self>,
23        _: &mut Context<'_>,
24        _: &mut tokio::io::ReadBuf<'_>,
25    ) -> Poll<std::io::Result<()>> {
26        Poll::Ready(Err(std::io::Error::new(
27            std::io::ErrorKind::Other,
28            "should not be called",
29        )))
30    }
31}
32
33impl AsyncWrite for NoopStream {
34    fn poll_write(
35        self: Pin<&mut Self>,
36        _: &mut Context<'_>,
37        _: &[u8],
38    ) -> Poll<std::io::Result<usize>> {
39        Poll::Ready(Err(std::io::Error::new(
40            std::io::ErrorKind::Other,
41            "should not be called",
42        )))
43    }
44
45    fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<std::io::Result<()>> {
46        Poll::Ready(Err(std::io::Error::new(
47            std::io::ErrorKind::Other,
48            "should not be called",
49        )))
50    }
51
52    fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<std::io::Result<()>> {
53        Poll::Ready(Err(std::io::Error::new(
54            std::io::ErrorKind::Other,
55            "should not be called",
56        )))
57    }
58}
59
60impl wrpc_transport::Index<Self> for NoopStream {
61    fn index(&self, _: &[usize]) -> anyhow::Result<Self> {
62        anyhow::bail!("should not be called")
63    }
64}
65
66/// Pack a [`wrpc_transport::Encode`] into a singular byte buffer `dst`.
67///
68/// This function does not support asynchronous values and will return an error is such a value is
69/// passed in.
70///
71/// This is unstable API, which will be deprecated once feature-complete "packing" functionality is available in [`wrpc_transport`].
72/// Track <https://github.com/bytecodealliance/wrpc/issues/25> for updates.
73pub fn pack<T: Encode<NoopStream>>(
74    v: T,
75    dst: &mut BytesMut,
76) -> Result<(), <T::Encoder as Encoder<T>>::Error> {
77    let mut enc = T::Encoder::default();
78    enc.encode(v, dst)?;
79    if enc.take_deferred().is_some() {
80        return Err(std::io::Error::new(
81            std::io::ErrorKind::InvalidData,
82            "value contains pending asynchronous values and cannot be packed",
83        )
84        .into());
85    }
86    Ok(())
87}
88
89/// Unpack a [`wrpc_transport::Decode`] from a byte buffer `dst`.
90///
91/// This function does not support asynchronous values and will return an error if `buf` contains pending async values.
92///
93/// If this function returns an error, contents of `buf` are undefined.
94///
95/// This is unstable API, which will be deprecated once feature-complete "unpacking" functionality is available in [`wrpc_transport`].
96/// Track <https://github.com/bytecodealliance/wrpc/issues/25> for updates.
97pub fn unpack<T: Decode<NoopStream>>(
98    buf: &mut BytesMut,
99) -> Result<T, <T::Decoder as Decoder>::Error> {
100    let mut dec = T::Decoder::default();
101    let v = dec.decode(buf)?;
102    let v = v.ok_or_else(|| {
103        std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "buffer is incomplete")
104    })?;
105    if dec.take_deferred().is_some() {
106        return Err(std::io::Error::new(
107            std::io::ErrorKind::InvalidData,
108            "buffer contains pending asynchronous values and cannot be unpacked",
109        )
110        .into());
111    }
112    Ok(v)
113}