valence_protocol/
raw.rs

1use std::io::Write;
2use std::mem;
3
4use anyhow::ensure;
5use derive_more::{Deref, DerefMut, From, Into};
6
7use crate::{Bounded, Decode, Encode};
8
9/// While [encoding], the contained slice is written directly to the output
10/// without any length prefix or metadata.
11///
12/// While [decoding], the remainder of the input is returned as the contained
13/// slice. The input will be at the EOF state after this is decoded.
14///
15/// [encoding]: Encode
16/// [decoding]: Decode
17#[derive(
18    Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug, Deref, DerefMut, From, Into,
19)]
20pub struct RawBytes<'a>(pub &'a [u8]);
21
22impl Encode for RawBytes<'_> {
23    fn encode(&self, mut w: impl Write) -> anyhow::Result<()> {
24        Ok(w.write_all(self.0)?)
25    }
26}
27
28impl<'a> Decode<'a> for RawBytes<'a> {
29    fn decode(r: &mut &'a [u8]) -> anyhow::Result<Self> {
30        Ok(Self(mem::take(r)))
31    }
32}
33
34/// Raises an encoding error if the inner slice is longer than `MAX_BYTES`.
35impl<const MAX_BYTES: usize> Encode for Bounded<RawBytes<'_>, MAX_BYTES> {
36    fn encode(&self, w: impl Write) -> anyhow::Result<()> {
37        ensure!(
38            self.len() <= MAX_BYTES,
39            "cannot encode more than {MAX_BYTES} raw bytes (got {} bytes)",
40            self.len()
41        );
42
43        self.0.encode(w)
44    }
45}
46
47/// Raises a decoding error if the remainder of the input is larger than
48/// `MAX_BYTES`.
49impl<'a, const MAX_BYTES: usize> Decode<'a> for Bounded<RawBytes<'a>, MAX_BYTES> {
50    fn decode(r: &mut &'a [u8]) -> anyhow::Result<Self> {
51        ensure!(
52            r.len() <= MAX_BYTES,
53            "remainder of input exceeds max of {MAX_BYTES} bytes (got {} bytes)",
54            r.len()
55        );
56
57        Ok(Bounded(RawBytes::decode(r)?))
58    }
59}