Skip to main content

tributary_framework/
read_write.rs

1use alloc::vec::Vec;
2use std::io;
3
4/// An item which can be read and written.
5pub trait ReadWrite: Sized {
6  /// Read an instance of `Self`.
7  ///
8  /// If the reader yields a reachable serialization of a value, it MUST be readable. In other
9  /// words, the following round-trip MUST succeed:
10  ///
11  /// ```rs
12  /// let serialization = item.serialize();
13  /// let mut serialization = serialization.as_slice();
14  /// let item2 = I::read(&mut serialization).unwrap();
15  /// // Functional equivalence in all regards, not just `<I as PartialEq>::eq` returning `true`
16  /// assert_eq!(item, item2);
17  /// assert!(serialization.is_empty());
18  /// ```
19  ///
20  /// Additionally, the item MUST be self-delimited and MUST NOT read to the end.
21  fn read(reader: impl io::Read) -> io::Result<Self>;
22
23  /// Write the value of `self`.
24  ///
25  /// This MUST be infallible except if the writer fails.
26  fn write(&self, writer: impl io::Write) -> io::Result<()>;
27
28  /// Serialize `self` to a `Vec<u8>`.
29  ///
30  /// This is infallible as [`ReadWrite::write`] is infallible except if the writer fails, and
31  /// `<Vec<u8> as Write>` is infallible.
32  fn serialize(&self) -> Vec<u8> {
33    let mut result = Vec::with_capacity(96);
34    self.write(&mut result).expect("`<Vec<u8> as Write>` is infallible");
35    result
36  }
37}
38
39pub(crate) fn serialized_len(value: &impl ReadWrite) -> io::Result<usize> {
40  struct SerializedLength(usize);
41  impl io::Write for SerializedLength {
42    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
43      if buf.len() > (usize::MAX - self.0) {
44        Err(io::Error::new(
45          io::ErrorKind::StorageFull,
46          "serialization's length exceeded `usize::MAX`",
47        ))?;
48      }
49      self.0 += buf.len();
50      Ok(buf.len())
51    }
52    fn flush(&mut self) -> io::Result<()> {
53      Ok(())
54    }
55  }
56
57  let mut length = SerializedLength(0);
58  let () = value.write(&mut length)?;
59  Ok(length.0)
60}
61
62#[derive(Clone)]
63#[repr(transparent)]
64#[doc(hidden)]
65pub struct ReadWriteAsBorsh<RW: ReadWrite>(pub RW);
66impl<'rw, RW: ReadWrite> From<&'rw RW> for &'rw ReadWriteAsBorsh<RW> {
67  fn from(rw: &'rw RW) -> Self {
68    // SAFETY: `repr(transparent)`
69    unsafe { &*core::ptr::from_ref(rw).cast::<ReadWriteAsBorsh<RW>>() }
70  }
71}
72impl<RW: ReadWrite> borsh::BorshSerialize for ReadWriteAsBorsh<RW> {
73  fn serialize<W: io::Write>(&self, writer: &mut W) -> Result<(), io::Error> {
74    ReadWrite::write(&self.0, writer)
75  }
76}
77impl<RW: ReadWrite> borsh::BorshDeserialize for ReadWriteAsBorsh<RW> {
78  fn deserialize_reader<R: io::Read>(reader: &mut R) -> Result<Self, io::Error> {
79    ReadWrite::read(reader).map(Self)
80  }
81}
82
83mod fixed_write {
84  use core::mem::MaybeUninit;
85  use std::io;
86
87  pub struct FixedWrite<'buf>(&'buf mut [MaybeUninit<u8>]);
88  impl io::Write for FixedWrite<'_> {
89    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
90      if self.0.is_empty() && (!buf.is_empty()) {
91        Err(io::Error::new(
92          io::ErrorKind::StorageFull,
93          "serialization's length exceeded fixed buffer's size",
94        ))?;
95      }
96
97      let len_to_copy = self.0.len().min(buf.len());
98      let dest = self.0.split_off_mut(.. len_to_copy).unwrap();
99      unsafe {
100        const {
101          assert!(core::mem::align_of::<u8>() == 1, "all `u8` pointers are inherently aligned");
102        }
103        dest
104          .as_mut_ptr()
105          .copy_from_nonoverlapping(buf.as_ptr().cast::<MaybeUninit<u8>>(), len_to_copy);
106      }
107      Ok(len_to_copy)
108    }
109
110    fn flush(&mut self) -> io::Result<()> {
111      Ok(())
112    }
113  }
114  impl Drop for FixedWrite<'_> {
115    fn drop(&mut self) {
116      assert!(self.0.is_empty());
117    }
118  }
119
120  /// Write the value to a fixed-length buffer.
121  ///
122  /// The value's serialization MUST be exactly this length. The write function MUST only fail if
123  /// the writer is fallible.
124  #[doc(hidden)]
125  pub fn fixed_write<const LEN: usize>(
126    write: impl Fn(&mut FixedWrite<'_>) -> std::io::Result<()>,
127  ) -> [u8; LEN] {
128    let mut serialization = MaybeUninit::<[u8; LEN]>::uninit();
129    {
130      let mut serialization = FixedWrite(serialization.as_mut());
131      write(&mut serialization).unwrap();
132    }
133    // SAFETY: `FixedWrite` panics on drop if it doesn't write to the entire buffer
134    unsafe { serialization.assume_init() }
135  }
136}
137pub use fixed_write::fixed_write;