integer_encoding/
writer.rs

1use std::io::{Result, Write};
2
3use crate::fixed::FixedInt;
4use crate::varint::VarInt;
5
6#[cfg(feature = "tokio_async")]
7use tokio::io::{AsyncWrite, AsyncWriteExt};
8
9#[cfg(feature = "futures_async")]
10use futures_util::{io::AsyncWrite, io::AsyncWriteExt};
11
12/// A trait for writing integers in VarInt encoding to any `Write` type. This packs encoding and
13/// writing into one step.
14pub trait VarIntWriter {
15    fn write_varint<VI: VarInt>(&mut self, n: VI) -> Result<usize>;
16}
17
18/// Like VarIntWriter, but asynchronous.
19#[cfg(any(feature = "tokio_async", feature = "futures_async"))]
20#[async_trait::async_trait]
21pub trait VarIntAsyncWriter {
22    /// Write a VarInt integer to an asynchronous writer.
23    async fn write_varint_async<VI: VarInt + Send>(&mut self, n: VI) -> Result<usize>;
24}
25
26#[cfg(any(feature = "tokio_async", feature = "futures_async"))]
27#[async_trait::async_trait]
28impl<AW: AsyncWrite + Send + Unpin> VarIntAsyncWriter for AW {
29    async fn write_varint_async<VI: VarInt + Send>(&mut self, n: VI) -> Result<usize> {
30        let mut buf = [0 as u8; 10];
31        let b = n.encode_var(&mut buf);
32        self.write_all(&buf[0..b]).await?;
33        Ok(b)
34    }
35}
36
37impl<Inner: Write> VarIntWriter for Inner {
38    fn write_varint<VI: VarInt>(&mut self, n: VI) -> Result<usize> {
39        let mut buf = [0 as u8; 10];
40        let used = n.encode_var(&mut buf[..]);
41
42        self.write_all(&buf[0..used])?;
43        Ok(used)
44    }
45}
46
47/// A trait for writing integers without encoding (i.e. `FixedInt`) to any `Write` type.
48pub trait FixedIntWriter {
49    fn write_fixedint<FI: FixedInt>(&mut self, n: FI) -> Result<usize>;
50}
51
52#[cfg(any(feature = "tokio_async", feature = "futures_async"))]
53#[async_trait::async_trait]
54pub trait FixedIntAsyncWriter {
55    async fn write_fixedint_async<FI: FixedInt + Send>(&mut self, n: FI) -> Result<usize>;
56}
57
58#[cfg(any(feature = "tokio_async", feature = "futures_async"))]
59#[async_trait::async_trait]
60impl<AW: AsyncWrite + Unpin + Send> FixedIntAsyncWriter for AW {
61    async fn write_fixedint_async<FI: FixedInt + Send>(&mut self, n: FI) -> Result<usize> {
62        let mut buf = [0 as u8; 8];
63        n.encode_fixed(&mut buf[0..FI::required_space()]);
64        self.write_all(&buf[0..FI::required_space()]).await?;
65        Ok(FI::REQUIRED_SPACE)
66    }
67}
68
69impl<W: Write> FixedIntWriter for W {
70    fn write_fixedint<FI: FixedInt>(&mut self, n: FI) -> Result<usize> {
71        let mut buf = [0 as u8; 8];
72        n.encode_fixed(&mut buf[0..FI::required_space()]);
73
74        self.write_all(&buf[0..FI::required_space()])?;
75        Ok(FI::REQUIRED_SPACE)
76    }
77}