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#[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
34impl<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
47impl<'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}