tributary_framework/
read_write.rs1use alloc::vec::Vec;
2use std::io;
3
4pub trait ReadWrite: Sized {
6 fn read(reader: impl io::Read) -> io::Result<Self>;
22
23 fn write(&self, writer: impl io::Write) -> io::Result<()>;
27
28 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 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 #[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 unsafe { serialization.assume_init() }
135 }
136}
137pub use fixed_write::fixed_write;