1use std::io::Write;
2use std::mem;
34use anyhow::ensure;
5use derive_more::{Deref, DerefMut, From, Into};
67use crate::{Bounded, Decode, Encode};
89/// 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]);
2122impl Encode for RawBytes<'_> {
23fn encode(&self, mut w: impl Write) -> anyhow::Result<()> {
24Ok(w.write_all(self.0)?)
25 }
26}
2728impl<'a> Decode<'a> for RawBytes<'a> {
29fn decode(r: &mut &'a [u8]) -> anyhow::Result<Self> {
30Ok(Self(mem::take(r)))
31 }
32}
3334/// Raises an encoding error if the inner slice is longer than `MAX_BYTES`.
35impl<const MAX_BYTES: usize> Encode for Bounded<RawBytes<'_>, MAX_BYTES> {
36fn encode(&self, w: impl Write) -> anyhow::Result<()> {
37ensure!(
38self.len() <= MAX_BYTES,
39"cannot encode more than {MAX_BYTES} raw bytes (got {} bytes)",
40self.len()
41 );
4243self.0.encode(w)
44 }
45}
4647/// 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> {
50fn decode(r: &mut &'a [u8]) -> anyhow::Result<Self> {
51ensure!(
52 r.len() <= MAX_BYTES,
53"remainder of input exceeds max of {MAX_BYTES} bytes (got {} bytes)",
54 r.len()
55 );
5657Ok(Bounded(RawBytes::decode(r)?))
58 }
59}