Skip to main content

ab_core_primitives/pieces/
piece.rs

1#[cfg(test)]
2mod tests;
3
4use crate::pieces::{InnerPiece, PieceHeader, Record};
5use ab_aligned_buffer::alignment::{Align1, Alignment};
6use ab_aligned_buffer::{OwnedAlignedBuffer, SharedAlignedBuffer};
7use ab_io_type::trivial_type::TrivialType;
8use core::fmt;
9use core::hash::{Hash, Hasher};
10use core::ops::{Deref, DerefMut};
11#[cfg(feature = "scale-codec")]
12use parity_scale_codec::{Decode, Encode, EncodeLike, Input, Output};
13#[cfg(feature = "serde")]
14use serde::de::Visitor;
15#[cfg(feature = "serde")]
16use serde::{Deserialize, Deserializer, Serialize, Serializer};
17
18/// A piece of archival history.
19///
20/// This version is allocated on the heap, for stack-allocated piece see [`InnerPiece`].
21///
22/// Internally piece contains a record and corresponding proof that together with segment
23/// root of the segment this piece belongs to can be used to verify that a piece belongs to
24/// the actual archival history of the blockchain.
25///
26/// Piece is a shared buffer, which is cheap to clone. Mutable access to a piece whose allocation is
27/// still shared (with other pieces or with [`FlatPieces`] it was created from, for example) copies
28/// it into a new allocation first.
29///
30/// [`FlatPieces`]: crate::pieces::FlatPieces
31#[derive(Clone)]
32pub struct Piece(pub(super) SharedAlignedBuffer<Align1>);
33
34impl fmt::Debug for Piece {
35    #[inline]
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        for byte in self.as_ref() {
38            write!(f, "{byte:02x}")?;
39        }
40        Ok(())
41    }
42}
43
44impl PartialEq for Piece {
45    #[inline]
46    fn eq(&self, other: &Self) -> bool {
47        self.as_ref() == other.as_ref()
48    }
49}
50
51impl Eq for Piece {}
52
53impl Hash for Piece {
54    #[inline]
55    fn hash<H>(&self, state: &mut H)
56    where
57        H: Hasher,
58    {
59        self.as_ref().hash(state);
60    }
61}
62
63/// Encoded as bytes of the piece without length, since the size of a piece is fixed
64#[cfg(feature = "scale-codec")]
65impl Encode for Piece {
66    #[inline]
67    fn size_hint(&self) -> usize {
68        Self::SIZE
69    }
70
71    #[inline]
72    fn encode_to<O>(&self, dest: &mut O)
73    where
74        O: Output + ?Sized,
75    {
76        dest.write(self.as_ref());
77    }
78
79    #[inline]
80    fn using_encoded<R, F>(&self, f: F) -> R
81    where
82        F: FnOnce(&[u8]) -> R,
83    {
84        f(self.as_ref())
85    }
86
87    #[inline]
88    fn encoded_size(&self) -> usize {
89        Self::SIZE
90    }
91}
92
93#[cfg(feature = "scale-codec")]
94impl EncodeLike for Piece {}
95
96#[cfg(feature = "scale-codec")]
97impl Decode for Piece {
98    fn decode<I>(input: &mut I) -> Result<Self, parity_scale_codec::Error>
99    where
100        I: Input,
101    {
102        input.on_before_alloc_mem(Self::SIZE)?;
103        let mut buffer = OwnedAlignedBuffer::<Align1>::zeroed(Self::SIZE_U32);
104        input
105            .read(buffer.as_mut_slice())
106            .map_err(|error| error.chain("Could not decode `Piece`"))?;
107
108        Ok(Self(buffer.into_shared()))
109    }
110
111    #[inline]
112    fn encoded_fixed_size() -> Option<usize> {
113        Some(Self::SIZE)
114    }
115}
116
117/// Serialized as a hex string in human-readable formats and as bytes otherwise
118#[cfg(feature = "serde")]
119impl Serialize for Piece {
120    #[inline]
121    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
122    where
123        S: Serializer,
124    {
125        if serializer.is_human_readable() {
126            hex::serde::serialize(self.as_ref(), serializer)
127        } else {
128            serializer.serialize_bytes(self.as_ref())
129        }
130    }
131}
132
133/// Accepts a hex string or bytes of a piece, contents are written into a new buffer
134/// directly
135#[cfg(feature = "serde")]
136struct PieceVisitor;
137
138#[cfg(feature = "serde")]
139impl Visitor<'_> for PieceVisitor {
140    type Value = Piece;
141
142    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
143        write!(formatter, "{} bytes or a hex string of them", Piece::SIZE)
144    }
145
146    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
147    where
148        E: serde::de::Error,
149    {
150        let mut buffer = OwnedAlignedBuffer::<Align1>::zeroed(Piece::SIZE_U32);
151        hex::decode_to_slice(v, buffer.as_mut_slice()).map_err(E::custom)?;
152
153        Ok(Piece(buffer.into_shared()))
154    }
155
156    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
157    where
158        E: serde::de::Error,
159    {
160        Piece::try_from(v).map_err(|()| E::invalid_length(v.len(), &self))
161    }
162}
163
164#[cfg(feature = "serde")]
165impl<'de> Deserialize<'de> for Piece {
166    #[inline]
167    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
168    where
169        D: Deserializer<'de>,
170    {
171        if deserializer.is_human_readable() {
172            deserializer.deserialize_str(PieceVisitor)
173        } else {
174            deserializer.deserialize_bytes(PieceVisitor)
175        }
176    }
177}
178
179impl Default for Piece {
180    #[inline]
181    fn default() -> Self {
182        Self(OwnedAlignedBuffer::<Align1>::zeroed(Self::SIZE_U32).into_shared())
183    }
184}
185
186impl TryFrom<&[u8]> for Piece {
187    type Error = ();
188
189    #[inline]
190    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
191        if slice.len() != Self::SIZE {
192            return Err(());
193        }
194
195        Ok(Self(SharedAlignedBuffer::from_bytes(slice)))
196    }
197}
198
199impl<A> TryFrom<SharedAlignedBuffer<A>> for Piece
200where
201    A: Alignment,
202{
203    type Error = ();
204
205    /// Uses the buffer without copying it
206    #[inline]
207    fn try_from(buffer: SharedAlignedBuffer<A>) -> Result<Self, Self::Error> {
208        if buffer.len() != Self::SIZE_U32 {
209            return Err(());
210        }
211
212        Ok(Self(buffer.into_start_align()))
213    }
214}
215
216impl<A> TryFrom<OwnedAlignedBuffer<A>> for Piece
217where
218    A: Alignment,
219{
220    type Error = ();
221
222    /// Uses the buffer without copying it
223    #[inline]
224    fn try_from(buffer: OwnedAlignedBuffer<A>) -> Result<Self, Self::Error> {
225        Self::try_from(buffer.into_shared())
226    }
227}
228
229impl From<&InnerPiece> for Piece {
230    #[inline]
231    fn from(value: &InnerPiece) -> Self {
232        Self(SharedAlignedBuffer::from_bytes(value.as_bytes()))
233    }
234}
235
236impl From<Piece> for SharedAlignedBuffer<Align1> {
237    #[inline]
238    fn from(piece: Piece) -> Self {
239        piece.0
240    }
241}
242
243impl Deref for Piece {
244    type Target = InnerPiece;
245
246    #[inline]
247    fn deref(&self) -> &Self::Target {
248        // SAFETY: Piece bytes are always `InnerPiece::SIZE` long (checked in constructors),
249        // `InnerPiece` has alignment of 1 and any bit pattern is a valid value (both checked
250        // next to its definition)
251        unsafe { InnerPiece::from_bytes_unchecked(self.as_ref()) }
252    }
253}
254
255impl DerefMut for Piece {
256    #[inline]
257    fn deref_mut(&mut self) -> &mut Self::Target {
258        // SAFETY: Piece bytes are always `InnerPiece::SIZE` long (checked in constructors),
259        // `InnerPiece` has alignment of 1 and any bit pattern is a valid value (both checked
260        // next to its definition)
261        unsafe { InnerPiece::from_bytes_mut_unchecked(self.as_mut()) }
262    }
263}
264
265impl AsRef<[u8]> for Piece {
266    #[inline]
267    fn as_ref(&self) -> &[u8] {
268        self.0.as_slice()
269    }
270}
271
272impl AsMut<[u8]> for Piece {
273    /// Copies the piece into a new allocation first if its allocation is still shared
274    #[inline]
275    fn as_mut(&mut self) -> &mut [u8] {
276        self.0.make_mut()
277    }
278}
279
280impl Piece {
281    /// Size of a piece (in bytes)
282    pub const SIZE: usize = InnerPiece::SIZE;
283    /// [`Self::SIZE`] as `u32`, the type of lengths of buffers
284    pub(super) const SIZE_U32: u32 = {
285        assert!(Self::SIZE <= u32::MAX as usize);
286        Self::SIZE as u32
287    };
288
289    /// Create a piece from its header and record.
290    ///
291    /// Contents are written into a new allocation directly, without zeroing it first or going
292    /// through the stack.
293    pub fn from_parts(header: &PieceHeader, record: &Record) -> Self {
294        let mut buffer = OwnedAlignedBuffer::<Align1>::with_capacity(Self::SIZE_U32);
295        let inner_piece = buffer
296            .spare_capacity_mut()
297            .as_mut_ptr()
298            .cast::<InnerPiece>();
299        // SAFETY: Capacity is sufficient for `InnerPiece`, whose alignment is `1`. Both fields are
300        // written, which initializes the whole `InnerPiece` since it has no padding.
301        unsafe {
302            (&raw mut (*inner_piece).header).write(*header);
303            (&raw mut (*inner_piece).record).copy_from_nonoverlapping(record, 1);
304            buffer.set_len(Self::SIZE_U32);
305        }
306
307        Self(buffer.into_shared())
308    }
309
310    /// Shared buffer with the contents of the piece
311    #[inline(always)]
312    pub fn buffer(&self) -> &SharedAlignedBuffer<Align1> {
313        &self.0
314    }
315}