ab_core_primitives/pieces/
piece.rs1#[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#[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#[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#[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#[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 #[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 #[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 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 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 #[inline]
275 fn as_mut(&mut self) -> &mut [u8] {
276 self.0.make_mut()
277 }
278}
279
280impl Piece {
281 pub const SIZE: usize = InnerPiece::SIZE;
283 pub(super) const SIZE_U32: u32 = {
285 assert!(Self::SIZE <= u32::MAX as usize);
286 Self::SIZE as u32
287 };
288
289 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 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 #[inline(always)]
312 pub fn buffer(&self) -> &SharedAlignedBuffer<Align1> {
313 &self.0
314 }
315}