Skip to main content

subspace_core_primitives/
pieces.rs

1//! Pieces-related data structures.
2
3#[cfg(not(feature = "std"))]
4extern crate alloc;
5
6use crate::ScalarBytes;
7use crate::segments::{ArchivedHistorySegment, RecordedHistorySegment, SegmentIndex};
8#[cfg(feature = "serde")]
9use ::serde::{Deserialize, Serialize};
10#[cfg(feature = "serde")]
11use ::serde::{Deserializer, Serializer};
12#[cfg(not(feature = "std"))]
13use alloc::boxed::Box;
14#[cfg(not(feature = "std"))]
15use alloc::format;
16#[cfg(not(feature = "std"))]
17use alloc::vec::Vec;
18use bytes::{Bytes, BytesMut};
19use core::array::TryFromSliceError;
20use core::hash::{Hash, Hasher};
21use core::iter::Step;
22use core::{fmt, mem, slice};
23use derive_more::with_trait::{
24    Add, AddAssign, AsMut, AsRef, Deref, DerefMut, Display, Div, DivAssign, From, Into, Mul,
25    MulAssign, Sub, SubAssign,
26};
27use parity_scale_codec::{
28    Decode, DecodeWithMemTracking, Encode, EncodeLike, Input, MaxEncodedLen, Output,
29};
30#[cfg(feature = "parallel")]
31use rayon::prelude::*;
32use scale_info::build::Fields;
33use scale_info::{Path, Type, TypeInfo};
34#[cfg(feature = "serde")]
35use serde_big_array::BigArray;
36
37/// Piece index in consensus
38#[derive(
39    Debug,
40    Display,
41    Default,
42    Copy,
43    Clone,
44    Ord,
45    PartialOrd,
46    Eq,
47    PartialEq,
48    Hash,
49    Encode,
50    Decode,
51    Add,
52    AddAssign,
53    Sub,
54    SubAssign,
55    Mul,
56    MulAssign,
57    Div,
58    DivAssign,
59    TypeInfo,
60    MaxEncodedLen,
61)]
62#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
63#[repr(transparent)]
64pub struct PieceIndex(u64);
65
66impl Step for PieceIndex {
67    #[inline]
68    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
69        u64::steps_between(&start.0, &end.0)
70    }
71
72    #[inline]
73    fn forward_checked(start: Self, count: usize) -> Option<Self> {
74        u64::forward_checked(start.0, count).map(Self)
75    }
76
77    #[inline]
78    fn forward_overflowing(start: Self, count: usize) -> (Self, bool) {
79        let (n, overflowing) = u64::forward_overflowing(start.0, count);
80        (Self(n), overflowing)
81    }
82
83    #[inline]
84    fn backward_checked(start: Self, count: usize) -> Option<Self> {
85        u64::backward_checked(start.0, count).map(Self)
86    }
87
88    #[inline]
89    fn backward_overflowing(start: Self, count: usize) -> (Self, bool) {
90        let (n, overflowing) = u64::backward_overflowing(start.0, count);
91        (Self(n), overflowing)
92    }
93}
94
95impl From<u64> for PieceIndex {
96    #[inline]
97    fn from(original: u64) -> Self {
98        Self(original)
99    }
100}
101
102impl From<PieceIndex> for u64 {
103    #[inline]
104    fn from(original: PieceIndex) -> Self {
105        original.0
106    }
107}
108
109impl PieceIndex {
110    /// Size in bytes.
111    pub const SIZE: usize = mem::size_of::<u64>();
112    /// Piece index 0.
113    pub const ZERO: PieceIndex = PieceIndex(0);
114    /// Piece index 1.
115    pub const ONE: PieceIndex = PieceIndex(1);
116
117    /// Create new instance
118    #[inline]
119    pub const fn new(n: u64) -> Self {
120        Self(n)
121    }
122
123    /// Create piece index from bytes.
124    #[inline]
125    pub const fn from_bytes(bytes: [u8; Self::SIZE]) -> Self {
126        Self(u64::from_le_bytes(bytes))
127    }
128
129    /// Convert piece index to bytes.
130    #[inline]
131    pub const fn to_bytes(self) -> [u8; Self::SIZE] {
132        self.0.to_le_bytes()
133    }
134
135    /// Segment index piece index corresponds to
136    #[inline]
137    pub const fn segment_index(&self) -> SegmentIndex {
138        SegmentIndex::new(self.0 / ArchivedHistorySegment::NUM_PIECES as u64)
139    }
140
141    /// Position of a piece in a segment
142    #[inline]
143    pub const fn position(&self) -> u32 {
144        // Position is statically guaranteed to fit into u32
145        (self.0 % ArchivedHistorySegment::NUM_PIECES as u64) as u32
146    }
147
148    /// Position of a source piece in the source pieces for a segment.
149    /// Panics if the piece is not a source piece.
150    #[inline]
151    pub const fn source_position(&self) -> u32 {
152        assert!(self.is_source());
153
154        let source_start = self.position() / RecordedHistorySegment::ERASURE_CODING_RATE.1 as u32
155            * RecordedHistorySegment::ERASURE_CODING_RATE.0 as u32;
156        let source_offset = self.position() % RecordedHistorySegment::ERASURE_CODING_RATE.1 as u32;
157
158        source_start + source_offset
159    }
160
161    /// Returns the piece index for a source position and segment index.
162    /// Overflows to the next segment if the position is greater than the last source position.
163    #[inline]
164    pub const fn from_source_position(
165        source_position: u32,
166        segment_index: SegmentIndex,
167    ) -> PieceIndex {
168        let source_position = source_position as u64;
169        let start = source_position / RecordedHistorySegment::ERASURE_CODING_RATE.0 as u64
170            * RecordedHistorySegment::ERASURE_CODING_RATE.1 as u64;
171        let offset = source_position % RecordedHistorySegment::ERASURE_CODING_RATE.0 as u64;
172
173        PieceIndex(segment_index.first_piece_index().0 + start + offset)
174    }
175
176    /// Is this piece index a source piece?
177    #[inline]
178    pub const fn is_source(&self) -> bool {
179        // Source pieces are interleaved with parity pieces, source first
180        self.0 % (RecordedHistorySegment::ERASURE_CODING_RATE.1 as u64)
181            < (RecordedHistorySegment::ERASURE_CODING_RATE.0 as u64)
182    }
183
184    /// Returns the next source piece index.
185    /// Panics if the piece is not a source piece.
186    #[inline]
187    pub const fn next_source_index(&self) -> PieceIndex {
188        PieceIndex::from_source_position(self.source_position() + 1, self.segment_index())
189    }
190
191    /// Returns the previous source piece index, if there is one.
192    /// Panics if the piece is not a source piece.
193    #[inline]
194    pub const fn prev_source_index(&self) -> Option<PieceIndex> {
195        if self.source_position() == 0 {
196            // TODO: when Option::map or ? become const, use them here
197            match self.segment_index().checked_sub(SegmentIndex::ONE) {
198                Some(segment_index) => Some(PieceIndex::from_source_position(
199                    RecordedHistorySegment::NUM_RAW_RECORDS as u32 - 1,
200                    segment_index,
201                )),
202                None => None,
203            }
204        } else {
205            Some(PieceIndex::from_source_position(
206                self.source_position() - 1,
207                self.segment_index(),
208            ))
209        }
210    }
211}
212
213/// Piece offset in sector
214#[derive(
215    Debug,
216    Display,
217    Default,
218    Copy,
219    Clone,
220    Ord,
221    PartialOrd,
222    Eq,
223    PartialEq,
224    Hash,
225    Encode,
226    Decode,
227    Add,
228    AddAssign,
229    Sub,
230    SubAssign,
231    Mul,
232    MulAssign,
233    Div,
234    DivAssign,
235    TypeInfo,
236    MaxEncodedLen,
237    DecodeWithMemTracking,
238)]
239#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
240#[repr(transparent)]
241pub struct PieceOffset(u16);
242
243impl Step for PieceOffset {
244    #[inline]
245    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
246        u16::steps_between(&start.0, &end.0)
247    }
248
249    #[inline]
250    fn forward_checked(start: Self, count: usize) -> Option<Self> {
251        u16::forward_checked(start.0, count).map(Self)
252    }
253
254    #[inline]
255    fn forward_overflowing(start: Self, count: usize) -> (Self, bool) {
256        let (n, overflowing) = u16::forward_overflowing(start.0, count);
257        (Self(n), overflowing)
258    }
259
260    #[inline]
261    fn backward_checked(start: Self, count: usize) -> Option<Self> {
262        u16::backward_checked(start.0, count).map(Self)
263    }
264
265    #[inline]
266    fn backward_overflowing(start: Self, count: usize) -> (Self, bool) {
267        let (n, overflowing) = u16::backward_overflowing(start.0, count);
268        (Self(n), overflowing)
269    }
270}
271
272impl From<u16> for PieceOffset {
273    #[inline]
274    fn from(original: u16) -> Self {
275        Self(original)
276    }
277}
278
279impl From<PieceOffset> for u16 {
280    #[inline]
281    fn from(original: PieceOffset) -> Self {
282        original.0
283    }
284}
285
286impl From<PieceOffset> for u32 {
287    #[inline]
288    fn from(original: PieceOffset) -> Self {
289        Self::from(original.0)
290    }
291}
292
293impl From<PieceOffset> for u64 {
294    #[inline]
295    fn from(original: PieceOffset) -> Self {
296        Self::from(original.0)
297    }
298}
299
300impl From<PieceOffset> for usize {
301    #[inline]
302    fn from(original: PieceOffset) -> Self {
303        usize::from(original.0)
304    }
305}
306
307impl PieceOffset {
308    /// Piece index 0.
309    pub const ZERO: PieceOffset = PieceOffset(0);
310    /// Piece index 1.
311    pub const ONE: PieceOffset = PieceOffset(1);
312
313    /// Convert piece offset to bytes.
314    #[inline]
315    pub const fn to_bytes(self) -> [u8; mem::size_of::<u16>()] {
316        self.0.to_le_bytes()
317    }
318}
319
320/// Raw record contained within recorded history segment before archiving is applied.
321///
322/// NOTE: This is a stack-allocated data structure and can cause stack overflow!
323#[derive(Copy, Clone, Eq, PartialEq, Deref, DerefMut)]
324#[repr(transparent)]
325pub struct RawRecord([[u8; ScalarBytes::SAFE_BYTES]; Self::NUM_CHUNKS]);
326
327impl fmt::Debug for RawRecord {
328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329        write!(f, "{}", hex::encode(self.0.as_flattened()))
330    }
331}
332
333impl Default for RawRecord {
334    #[inline]
335    fn default() -> Self {
336        Self([Default::default(); Self::NUM_CHUNKS])
337    }
338}
339
340impl AsRef<[u8]> for RawRecord {
341    #[inline]
342    fn as_ref(&self) -> &[u8] {
343        self.0.as_slice().as_flattened()
344    }
345}
346
347impl AsMut<[u8]> for RawRecord {
348    #[inline]
349    fn as_mut(&mut self) -> &mut [u8] {
350        self.0.as_mut_slice().as_flattened_mut()
351    }
352}
353
354impl From<&RawRecord> for &[[u8; ScalarBytes::SAFE_BYTES]; RawRecord::NUM_CHUNKS] {
355    #[inline]
356    fn from(value: &RawRecord) -> Self {
357        // SAFETY: `RawRecord` is `#[repr(transparent)]` and guaranteed to have the same memory
358        // layout
359        unsafe { mem::transmute(value) }
360    }
361}
362
363impl From<&[[u8; ScalarBytes::SAFE_BYTES]; RawRecord::NUM_CHUNKS]> for &RawRecord {
364    #[inline]
365    fn from(value: &[[u8; ScalarBytes::SAFE_BYTES]; RawRecord::NUM_CHUNKS]) -> Self {
366        // SAFETY: `RawRecord` is `#[repr(transparent)]` and guaranteed to have the same memory
367        // layout
368        unsafe { mem::transmute(value) }
369    }
370}
371
372impl From<&mut RawRecord> for &mut [[u8; ScalarBytes::SAFE_BYTES]; RawRecord::NUM_CHUNKS] {
373    #[inline]
374    fn from(value: &mut RawRecord) -> Self {
375        // SAFETY: `RawRecord` is `#[repr(transparent)]` and guaranteed to have the same memory
376        // layout
377        unsafe { mem::transmute(value) }
378    }
379}
380
381impl From<&mut [[u8; ScalarBytes::SAFE_BYTES]; RawRecord::NUM_CHUNKS]> for &mut RawRecord {
382    #[inline]
383    fn from(value: &mut [[u8; ScalarBytes::SAFE_BYTES]; RawRecord::NUM_CHUNKS]) -> Self {
384        // SAFETY: `RawRecord` is `#[repr(transparent)]` and guaranteed to have the same memory
385        // layout
386        unsafe { mem::transmute(value) }
387    }
388}
389
390impl From<&RawRecord> for &[u8; ScalarBytes::SAFE_BYTES * RawRecord::NUM_CHUNKS] {
391    #[inline]
392    fn from(value: &RawRecord) -> Self {
393        // SAFETY: `RawRecord` is `#[repr(transparent)]` and guaranteed to have the same memory
394        // layout as inner array, while array of byte arrays has the same alignment as a single byte
395        unsafe { mem::transmute(value) }
396    }
397}
398
399impl From<&[u8; ScalarBytes::SAFE_BYTES * RawRecord::NUM_CHUNKS]> for &RawRecord {
400    #[inline]
401    fn from(value: &[u8; ScalarBytes::SAFE_BYTES * RawRecord::NUM_CHUNKS]) -> Self {
402        // SAFETY: `RawRecord` is `#[repr(transparent)]` and guaranteed to have the same memory
403        // layout as inner array, while array of byte arrays has the same alignment as a single byte
404        unsafe { mem::transmute(value) }
405    }
406}
407
408impl From<&mut RawRecord> for &mut [u8; ScalarBytes::SAFE_BYTES * RawRecord::NUM_CHUNKS] {
409    #[inline]
410    fn from(value: &mut RawRecord) -> Self {
411        // SAFETY: `RawRecord` is `#[repr(transparent)]` and guaranteed to have the same memory
412        // layout as inner array, while array of byte arrays has the same alignment as a single byte
413        unsafe { mem::transmute(value) }
414    }
415}
416
417impl From<&mut [u8; ScalarBytes::SAFE_BYTES * RawRecord::NUM_CHUNKS]> for &mut RawRecord {
418    #[inline]
419    fn from(value: &mut [u8; ScalarBytes::SAFE_BYTES * RawRecord::NUM_CHUNKS]) -> Self {
420        // SAFETY: `RawRecord` is `#[repr(transparent)]` and guaranteed to have the same memory
421        // layout as inner array, while array of byte arrays has the same alignment as a single byte
422        unsafe { mem::transmute(value) }
423    }
424}
425
426impl RawRecord {
427    /// Number of chunks (scalars) within one raw record.
428    pub const NUM_CHUNKS: usize = 2_usize.pow(15);
429    /// Size of raw record in bytes, is guaranteed to be a multiple of [`ScalarBytes::SAFE_BYTES`].
430    pub const SIZE: usize = ScalarBytes::SAFE_BYTES * Self::NUM_CHUNKS;
431
432    /// Create boxed value without hitting stack overflow
433    #[inline]
434    pub fn new_boxed() -> Box<Self> {
435        // TODO: Should have been just `::new()`, but https://github.com/rust-lang/rust/issues/53827
436        // SAFETY: Data structure filled with zeroes is a valid invariant
437        unsafe { Box::new_zeroed().assume_init() }
438    }
439
440    /// Convenient conversion from slice of record to underlying representation for efficiency
441    /// purposes.
442    #[inline]
443    pub fn slice_to_repr(value: &[Self]) -> &[[[u8; ScalarBytes::SAFE_BYTES]; Self::NUM_CHUNKS]] {
444        // SAFETY: `RawRecord` is `#[repr(transparent)]` and guaranteed to have the same memory
445        // layout
446        unsafe { mem::transmute(value) }
447    }
448
449    /// Convenient conversion from slice of underlying representation to record for efficiency
450    /// purposes.
451    #[inline]
452    pub fn slice_from_repr(value: &[[[u8; ScalarBytes::SAFE_BYTES]; Self::NUM_CHUNKS]]) -> &[Self] {
453        // SAFETY: `RawRecord` is `#[repr(transparent)]` and guaranteed to have the same memory
454        // layout
455        unsafe { mem::transmute(value) }
456    }
457
458    /// Convenient conversion from mutable slice of record to underlying representation for
459    /// efficiency purposes.
460    #[inline]
461    pub fn slice_mut_to_repr(
462        value: &mut [Self],
463    ) -> &mut [[[u8; ScalarBytes::SAFE_BYTES]; Self::NUM_CHUNKS]] {
464        // SAFETY: `RawRecord` is `#[repr(transparent)]` and guaranteed to have the same memory
465        // layout
466        unsafe { mem::transmute(value) }
467    }
468
469    /// Convenient conversion from mutable slice of underlying representation to record for
470    /// efficiency purposes.
471    #[inline]
472    pub fn slice_mut_from_repr(
473        value: &mut [[[u8; ScalarBytes::SAFE_BYTES]; Self::NUM_CHUNKS]],
474    ) -> &mut [Self] {
475        // SAFETY: `RawRecord` is `#[repr(transparent)]` and guaranteed to have the same memory
476        // layout
477        unsafe { mem::transmute(value) }
478    }
479}
480
481/// Record contained within a piece.
482///
483/// NOTE: This is a stack-allocated data structure and can cause stack overflow!
484#[derive(Copy, Clone, Eq, PartialEq, Deref, DerefMut)]
485#[repr(transparent)]
486pub struct Record([[u8; ScalarBytes::FULL_BYTES]; Self::NUM_CHUNKS]);
487
488impl fmt::Debug for Record {
489    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
490        write!(f, "{}", hex::encode(self.0.as_flattened()))
491    }
492}
493
494impl Default for Record {
495    #[inline]
496    fn default() -> Self {
497        Self([Default::default(); Self::NUM_CHUNKS])
498    }
499}
500
501impl AsRef<[u8]> for Record {
502    #[inline]
503    fn as_ref(&self) -> &[u8] {
504        self.0.as_flattened()
505    }
506}
507
508impl AsMut<[u8]> for Record {
509    #[inline]
510    fn as_mut(&mut self) -> &mut [u8] {
511        self.0.as_flattened_mut()
512    }
513}
514
515impl From<&Record> for &[[u8; ScalarBytes::FULL_BYTES]; Record::NUM_CHUNKS] {
516    #[inline]
517    fn from(value: &Record) -> Self {
518        // SAFETY: `Record` is `#[repr(transparent)]` and guaranteed to have the same memory layout
519        unsafe { mem::transmute(value) }
520    }
521}
522
523impl From<&[[u8; ScalarBytes::FULL_BYTES]; Record::NUM_CHUNKS]> for &Record {
524    #[inline]
525    fn from(value: &[[u8; ScalarBytes::FULL_BYTES]; Record::NUM_CHUNKS]) -> Self {
526        // SAFETY: `Record` is `#[repr(transparent)]` and guaranteed to have the same memory layout
527        unsafe { mem::transmute(value) }
528    }
529}
530
531impl From<&mut Record> for &mut [[u8; ScalarBytes::FULL_BYTES]; Record::NUM_CHUNKS] {
532    #[inline]
533    fn from(value: &mut Record) -> Self {
534        // SAFETY: `Record` is `#[repr(transparent)]` and guaranteed to have the same memory layout
535        unsafe { mem::transmute(value) }
536    }
537}
538
539impl From<&mut [[u8; ScalarBytes::FULL_BYTES]; Record::NUM_CHUNKS]> for &mut Record {
540    #[inline]
541    fn from(value: &mut [[u8; ScalarBytes::FULL_BYTES]; Record::NUM_CHUNKS]) -> Self {
542        // SAFETY: `Record` is `#[repr(transparent)]` and guaranteed to have the same memory layout
543        unsafe { mem::transmute(value) }
544    }
545}
546
547impl From<&Record> for &[u8; ScalarBytes::FULL_BYTES * Record::NUM_CHUNKS] {
548    #[inline]
549    fn from(value: &Record) -> Self {
550        // SAFETY: `Record` is `#[repr(transparent)]` and guaranteed to have the same memory layout
551        // as inner array, while array of byte arrays has the same alignment as a single byte
552        unsafe { mem::transmute(value) }
553    }
554}
555
556impl From<&[u8; ScalarBytes::FULL_BYTES * Record::NUM_CHUNKS]> for &Record {
557    #[inline]
558    fn from(value: &[u8; ScalarBytes::FULL_BYTES * Record::NUM_CHUNKS]) -> Self {
559        // SAFETY: `Record` is `#[repr(transparent)]` and guaranteed to have the same memory layout
560        // as inner array, while array of byte arrays has the same alignment as a single byte
561        unsafe { mem::transmute(value) }
562    }
563}
564
565impl From<&mut Record> for &mut [u8; ScalarBytes::FULL_BYTES * Record::NUM_CHUNKS] {
566    #[inline]
567    fn from(value: &mut Record) -> Self {
568        // SAFETY: `Record` is `#[repr(transparent)]` and guaranteed to have the same memory layout
569        // as inner array, while array of byte arrays has the same alignment as a single byte
570        unsafe { mem::transmute(value) }
571    }
572}
573
574impl From<&mut [u8; ScalarBytes::FULL_BYTES * Record::NUM_CHUNKS]> for &mut Record {
575    #[inline]
576    fn from(value: &mut [u8; ScalarBytes::FULL_BYTES * Record::NUM_CHUNKS]) -> Self {
577        // SAFETY: `Record` is `#[repr(transparent)]` and guaranteed to have the same memory layout
578        // as inner array, while array of byte arrays has the same alignment as a single byte
579        unsafe { mem::transmute(value) }
580    }
581}
582
583impl Record {
584    /// Number of chunks (scalars) within one record.
585    pub const NUM_CHUNKS: usize = RawRecord::NUM_CHUNKS;
586    /// Number of s-buckets contained within one record (and by extension sector).
587    ///
588    /// Essentially we chunk records into scalars and erasure code them.
589    pub const NUM_S_BUCKETS: usize = Self::NUM_CHUNKS
590        * RecordedHistorySegment::ERASURE_CODING_RATE.1
591        / RecordedHistorySegment::ERASURE_CODING_RATE.0;
592    /// Size of a segment record given the global piece size (in bytes) after erasure coding
593    /// [`RawRecord`], is guaranteed to be a multiple of [`ScalarBytes::FULL_BYTES`].
594    pub const SIZE: usize = ScalarBytes::FULL_BYTES * Self::NUM_CHUNKS;
595
596    /// Create boxed value without hitting stack overflow
597    #[inline]
598    pub fn new_boxed() -> Box<Self> {
599        // TODO: Should have been just `::new()`, but https://github.com/rust-lang/rust/issues/53827
600        // SAFETY: Data structure filled with zeroes is a valid invariant
601        unsafe { Box::new_zeroed().assume_init() }
602    }
603
604    /// Create vector filled with zeroe records without hitting stack overflow
605    #[inline]
606    pub fn new_zero_vec(length: usize) -> Vec<Self> {
607        // TODO: Should have been just `::new()`, but https://github.com/rust-lang/rust/issues/53827
608        // SAFETY: Data structure filled with zeroes is a valid invariant
609        unsafe { Box::<[Self]>::new_zeroed_slice(length).assume_init() }.into_vec()
610    }
611
612    /// Convenient conversion from slice of record to underlying representation for efficiency
613    /// purposes.
614    #[inline]
615    pub fn slice_to_repr(value: &[Self]) -> &[[[u8; ScalarBytes::FULL_BYTES]; Self::NUM_CHUNKS]] {
616        // SAFETY: `Record` is `#[repr(transparent)]` and guaranteed to have the same memory layout
617        unsafe { mem::transmute(value) }
618    }
619
620    /// Convenient conversion from slice of underlying representation to record for efficiency
621    /// purposes.
622    #[inline]
623    pub fn slice_from_repr(value: &[[[u8; ScalarBytes::FULL_BYTES]; Self::NUM_CHUNKS]]) -> &[Self] {
624        // SAFETY: `Record` is `#[repr(transparent)]` and guaranteed to have the same memory layout
625        unsafe { mem::transmute(value) }
626    }
627
628    /// Convenient conversion from mutable slice of record to underlying representation for
629    /// efficiency purposes.
630    #[inline]
631    pub fn slice_mut_to_repr(
632        value: &mut [Self],
633    ) -> &mut [[[u8; ScalarBytes::FULL_BYTES]; Self::NUM_CHUNKS]] {
634        // SAFETY: `Record` is `#[repr(transparent)]` and guaranteed to have the same memory layout
635        unsafe { mem::transmute(value) }
636    }
637
638    /// Convenient conversion from mutable slice of underlying representation to record for
639    /// efficiency purposes.
640    #[inline]
641    pub fn slice_mut_from_repr(
642        value: &mut [[[u8; ScalarBytes::FULL_BYTES]; Self::NUM_CHUNKS]],
643    ) -> &mut [Self] {
644        // SAFETY: `Record` is `#[repr(transparent)]` and guaranteed to have the same memory layout
645        unsafe { mem::transmute(value) }
646    }
647
648    /// Convert from a record to its raw bytes, assumes dealing with source record that only stores
649    /// safe bytes in its chunks.
650    #[inline]
651    pub fn to_raw_record_chunks(
652        &self,
653    ) -> impl DoubleEndedIterator<Item = &'_ [u8; ScalarBytes::SAFE_BYTES]> + '_ {
654        // We have zero byte padding from [`ScalarBytes::SAFE_BYTES`] to
655        // [`ScalarBytes::FULL_BYTES`] that we need to skip
656        self.iter()
657            .map(|bytes| bytes[1..].try_into().expect("Correct length; qed"))
658    }
659
660    /// Convert from a record to mutable raw bytes, assumes dealing with source record that only stores
661    /// safe bytes in its chunks.
662    #[inline]
663    pub fn to_mut_raw_record_chunks(
664        &mut self,
665    ) -> impl DoubleEndedIterator<Item = &'_ mut [u8; ScalarBytes::SAFE_BYTES]> + '_ {
666        self.iter_mut()
667            .map(|bytes| (&mut bytes[1..]).try_into().expect("Correct length; qed"))
668    }
669}
670
671/// Record commitment contained within a piece.
672#[derive(
673    Copy,
674    Clone,
675    Eq,
676    PartialEq,
677    Hash,
678    Deref,
679    DerefMut,
680    From,
681    Into,
682    Encode,
683    Decode,
684    TypeInfo,
685    MaxEncodedLen,
686    DecodeWithMemTracking,
687)]
688pub struct RecordCommitment([u8; RecordCommitment::SIZE]);
689
690impl fmt::Debug for RecordCommitment {
691    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
692        write!(f, "{}", hex::encode(self.0))
693    }
694}
695
696#[cfg(feature = "serde")]
697#[derive(Serialize, Deserialize)]
698#[serde(transparent)]
699struct RecordCommitmentBinary(#[serde(with = "BigArray")] [u8; RecordCommitment::SIZE]);
700
701#[cfg(feature = "serde")]
702#[derive(Serialize, Deserialize)]
703#[serde(transparent)]
704struct RecordCommitmentHex(#[serde(with = "hex")] [u8; RecordCommitment::SIZE]);
705
706#[cfg(feature = "serde")]
707impl Serialize for RecordCommitment {
708    #[inline]
709    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
710    where
711        S: Serializer,
712    {
713        if serializer.is_human_readable() {
714            RecordCommitmentHex(self.0).serialize(serializer)
715        } else {
716            RecordCommitmentBinary(self.0).serialize(serializer)
717        }
718    }
719}
720
721#[cfg(feature = "serde")]
722impl<'de> Deserialize<'de> for RecordCommitment {
723    #[inline]
724    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
725    where
726        D: Deserializer<'de>,
727    {
728        Ok(Self(if deserializer.is_human_readable() {
729            RecordCommitmentHex::deserialize(deserializer)?.0
730        } else {
731            RecordCommitmentBinary::deserialize(deserializer)?.0
732        }))
733    }
734}
735
736impl Default for RecordCommitment {
737    #[inline]
738    fn default() -> Self {
739        Self([0; Self::SIZE])
740    }
741}
742
743impl TryFrom<&[u8]> for RecordCommitment {
744    type Error = TryFromSliceError;
745
746    #[inline]
747    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
748        <[u8; Self::SIZE]>::try_from(slice).map(Self)
749    }
750}
751
752impl AsRef<[u8]> for RecordCommitment {
753    #[inline]
754    fn as_ref(&self) -> &[u8] {
755        &self.0
756    }
757}
758
759impl AsMut<[u8]> for RecordCommitment {
760    #[inline]
761    fn as_mut(&mut self) -> &mut [u8] {
762        &mut self.0
763    }
764}
765
766impl From<&RecordCommitment> for &[u8; RecordCommitment::SIZE] {
767    #[inline]
768    fn from(value: &RecordCommitment) -> Self {
769        // SAFETY: `RecordCommitment` is `#[repr(transparent)]` and guaranteed to have the same
770        // memory layout
771        unsafe { mem::transmute(value) }
772    }
773}
774
775impl From<&[u8; RecordCommitment::SIZE]> for &RecordCommitment {
776    #[inline]
777    fn from(value: &[u8; RecordCommitment::SIZE]) -> Self {
778        // SAFETY: `RecordCommitment` is `#[repr(transparent)]` and guaranteed to have the same
779        // memory layout
780        unsafe { mem::transmute(value) }
781    }
782}
783
784impl From<&mut RecordCommitment> for &mut [u8; RecordCommitment::SIZE] {
785    #[inline]
786    fn from(value: &mut RecordCommitment) -> Self {
787        // SAFETY: `RecordCommitment` is `#[repr(transparent)]` and guaranteed to have the same
788        // memory layout
789        unsafe { mem::transmute(value) }
790    }
791}
792
793impl From<&mut [u8; RecordCommitment::SIZE]> for &mut RecordCommitment {
794    #[inline]
795    fn from(value: &mut [u8; RecordCommitment::SIZE]) -> Self {
796        // SAFETY: `RecordCommitment` is `#[repr(transparent)]` and guaranteed to have the same
797        // memory layout
798        unsafe { mem::transmute(value) }
799    }
800}
801
802impl RecordCommitment {
803    /// Size of record commitment in bytes.
804    pub const SIZE: usize = 48;
805}
806
807/// Record witness contained within a piece.
808#[derive(
809    Copy,
810    Clone,
811    Eq,
812    PartialEq,
813    Hash,
814    Deref,
815    DerefMut,
816    From,
817    Into,
818    Encode,
819    Decode,
820    TypeInfo,
821    MaxEncodedLen,
822    DecodeWithMemTracking,
823)]
824pub struct RecordWitness([u8; RecordWitness::SIZE]);
825
826impl fmt::Debug for RecordWitness {
827    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
828        write!(f, "{}", hex::encode(self.0))
829    }
830}
831
832#[cfg(feature = "serde")]
833#[derive(Serialize, Deserialize)]
834#[serde(transparent)]
835struct RecordWitnessBinary(#[serde(with = "BigArray")] [u8; RecordWitness::SIZE]);
836
837#[cfg(feature = "serde")]
838#[derive(Serialize, Deserialize)]
839#[serde(transparent)]
840struct RecordWitnessHex(#[serde(with = "hex")] [u8; RecordWitness::SIZE]);
841
842#[cfg(feature = "serde")]
843impl Serialize for RecordWitness {
844    #[inline]
845    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
846    where
847        S: Serializer,
848    {
849        if serializer.is_human_readable() {
850            RecordWitnessHex(self.0).serialize(serializer)
851        } else {
852            RecordWitnessBinary(self.0).serialize(serializer)
853        }
854    }
855}
856
857#[cfg(feature = "serde")]
858impl<'de> Deserialize<'de> for RecordWitness {
859    #[inline]
860    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
861    where
862        D: Deserializer<'de>,
863    {
864        Ok(Self(if deserializer.is_human_readable() {
865            RecordWitnessHex::deserialize(deserializer)?.0
866        } else {
867            RecordWitnessBinary::deserialize(deserializer)?.0
868        }))
869    }
870}
871
872impl Default for RecordWitness {
873    #[inline]
874    fn default() -> Self {
875        Self([0; Self::SIZE])
876    }
877}
878
879impl TryFrom<&[u8]> for RecordWitness {
880    type Error = TryFromSliceError;
881
882    #[inline]
883    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
884        <[u8; Self::SIZE]>::try_from(slice).map(Self)
885    }
886}
887
888impl AsRef<[u8]> for RecordWitness {
889    #[inline]
890    fn as_ref(&self) -> &[u8] {
891        &self.0
892    }
893}
894
895impl AsMut<[u8]> for RecordWitness {
896    #[inline]
897    fn as_mut(&mut self) -> &mut [u8] {
898        &mut self.0
899    }
900}
901
902impl From<&RecordWitness> for &[u8; RecordWitness::SIZE] {
903    #[inline]
904    fn from(value: &RecordWitness) -> Self {
905        // SAFETY: `RecordWitness` is `#[repr(transparent)]` and guaranteed to have the same
906        // memory layout
907        unsafe { mem::transmute(value) }
908    }
909}
910
911impl From<&[u8; RecordWitness::SIZE]> for &RecordWitness {
912    #[inline]
913    fn from(value: &[u8; RecordWitness::SIZE]) -> Self {
914        // SAFETY: `RecordWitness` is `#[repr(transparent)]` and guaranteed to have the same
915        // memory layout
916        unsafe { mem::transmute(value) }
917    }
918}
919
920impl From<&mut RecordWitness> for &mut [u8; RecordWitness::SIZE] {
921    #[inline]
922    fn from(value: &mut RecordWitness) -> Self {
923        // SAFETY: `RecordWitness` is `#[repr(transparent)]` and guaranteed to have the same
924        // memory layout
925        unsafe { mem::transmute(value) }
926    }
927}
928
929impl From<&mut [u8; RecordWitness::SIZE]> for &mut RecordWitness {
930    #[inline]
931    fn from(value: &mut [u8; RecordWitness::SIZE]) -> Self {
932        // SAFETY: `RecordWitness` is `#[repr(transparent)]` and guaranteed to have the same
933        // memory layout
934        unsafe { mem::transmute(value) }
935    }
936}
937
938impl RecordWitness {
939    /// Size of record witness in bytes.
940    pub const SIZE: usize = 48;
941}
942
943enum CowBytes {
944    Shared(Bytes),
945    Owned(BytesMut),
946}
947
948impl fmt::Debug for CowBytes {
949    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
950        write!(f, "{}", hex::encode(self.as_ref()))
951    }
952}
953
954impl PartialEq for CowBytes {
955    fn eq(&self, other: &Self) -> bool {
956        self.as_ref().eq(other.as_ref())
957    }
958}
959
960impl Eq for CowBytes {}
961
962impl Hash for CowBytes {
963    fn hash<H: Hasher>(&self, state: &mut H) {
964        self.as_ref().hash(state)
965    }
966}
967
968impl Clone for CowBytes {
969    fn clone(&self) -> Self {
970        match self {
971            Self::Shared(bytes) => Self::Shared(bytes.clone()),
972            // Always return shared clone
973            Self::Owned(bytes) => Self::Shared(Bytes::copy_from_slice(bytes)),
974        }
975    }
976}
977
978impl AsRef<[u8]> for CowBytes {
979    fn as_ref(&self) -> &[u8] {
980        match self {
981            CowBytes::Shared(bytes) => bytes.as_ref(),
982            CowBytes::Owned(bytes) => bytes.as_ref(),
983        }
984    }
985}
986
987impl AsMut<[u8]> for CowBytes {
988    #[inline]
989    fn as_mut(&mut self) -> &mut [u8] {
990        match self {
991            CowBytes::Shared(bytes) => {
992                *self = CowBytes::Owned(BytesMut::from(mem::take(bytes)));
993
994                let CowBytes::Owned(bytes) = self else {
995                    unreachable!("Just replaced; qed");
996                };
997
998                bytes.as_mut()
999            }
1000            CowBytes::Owned(bytes) => bytes.as_mut(),
1001        }
1002    }
1003}
1004
1005/// A piece of archival history in Subspace Network.
1006///
1007/// This version is allocated on the heap, for stack-allocated piece see [`PieceArray`].
1008///
1009/// Internally piece contains a record and corresponding witness that together with segment
1010/// commitment of the segment this piece belongs to can be used to verify that a piece belongs to
1011/// the actual archival history of the blockchain.
1012#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1013pub struct Piece(CowBytes);
1014
1015impl Encode for Piece {
1016    #[inline]
1017    fn size_hint(&self) -> usize {
1018        self.as_ref().size_hint()
1019    }
1020
1021    #[inline]
1022    fn encode_to<O: Output + ?Sized>(&self, output: &mut O) {
1023        self.as_ref().encode_to(output)
1024    }
1025
1026    #[inline]
1027    fn encode(&self) -> Vec<u8> {
1028        self.as_ref().encode()
1029    }
1030
1031    #[inline]
1032    fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
1033        self.as_ref().using_encoded(f)
1034    }
1035}
1036
1037impl EncodeLike for Piece {}
1038
1039impl Decode for Piece {
1040    fn decode<I: Input>(input: &mut I) -> Result<Self, parity_scale_codec::Error> {
1041        let bytes =
1042            Bytes::decode(input).map_err(|error| error.chain("Could not decode `Piece`"))?;
1043
1044        if bytes.len() != Self::SIZE {
1045            return Err(
1046                parity_scale_codec::Error::from("Incorrect Piece length").chain(format!(
1047                    "Expected {} bytes, found {} bytes",
1048                    Self::SIZE,
1049                    bytes.len()
1050                )),
1051            );
1052        }
1053
1054        Ok(Piece(CowBytes::Shared(bytes)))
1055    }
1056}
1057
1058impl TypeInfo for Piece {
1059    type Identity = Self;
1060
1061    fn type_info() -> Type {
1062        Type::builder()
1063            .path(Path::new("Piece", module_path!()))
1064            .docs(&["A piece of archival history in Subspace Network"])
1065            .composite(
1066                Fields::unnamed().field(|f| f.ty::<[u8; Piece::SIZE]>().type_name("PieceArray")),
1067            )
1068    }
1069}
1070
1071#[cfg(feature = "serde")]
1072impl Serialize for Piece {
1073    #[inline]
1074    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1075    where
1076        S: Serializer,
1077    {
1078        let bytes = match &self.0 {
1079            CowBytes::Shared(bytes) => bytes.as_ref(),
1080            CowBytes::Owned(bytes) => bytes.as_ref(),
1081        };
1082
1083        if serializer.is_human_readable() {
1084            hex::serde::serialize(bytes, serializer)
1085        } else {
1086            bytes.serialize(serializer)
1087        }
1088    }
1089}
1090
1091#[cfg(feature = "serde")]
1092impl<'de> Deserialize<'de> for Piece {
1093    #[inline]
1094    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1095    where
1096        D: Deserializer<'de>,
1097    {
1098        let bytes = if deserializer.is_human_readable() {
1099            hex::serde::deserialize::<_, Vec<u8>>(deserializer).and_then(|bytes| {
1100                if bytes.len() == Piece::SIZE {
1101                    Ok(Bytes::from(bytes))
1102                } else {
1103                    Err(serde::de::Error::invalid_length(
1104                        bytes.len(),
1105                        &format!("Expected {} bytes", Piece::SIZE).as_str(),
1106                    ))
1107                }
1108            })?
1109        } else {
1110            Bytes::deserialize(deserializer)?
1111        };
1112
1113        Ok(Piece(CowBytes::Shared(bytes)))
1114    }
1115}
1116
1117impl Default for Piece {
1118    #[inline]
1119    fn default() -> Self {
1120        Self(CowBytes::Owned(BytesMut::zeroed(Self::SIZE)))
1121    }
1122}
1123
1124impl From<Piece> for Vec<u8> {
1125    #[inline]
1126    fn from(piece: Piece) -> Self {
1127        match piece.0 {
1128            CowBytes::Shared(bytes) => bytes.to_vec(),
1129            CowBytes::Owned(bytes) => Vec::from(bytes),
1130        }
1131    }
1132}
1133
1134impl TryFrom<&[u8]> for Piece {
1135    type Error = ();
1136
1137    #[inline]
1138    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
1139        if slice.len() != Self::SIZE {
1140            return Err(());
1141        }
1142
1143        Ok(Self(CowBytes::Shared(Bytes::copy_from_slice(slice))))
1144    }
1145}
1146
1147impl TryFrom<Vec<u8>> for Piece {
1148    type Error = ();
1149
1150    #[inline]
1151    fn try_from(vec: Vec<u8>) -> Result<Self, Self::Error> {
1152        if vec.len() != Self::SIZE {
1153            return Err(());
1154        }
1155
1156        Ok(Self(CowBytes::Shared(Bytes::from(vec))))
1157    }
1158}
1159
1160impl TryFrom<Bytes> for Piece {
1161    type Error = ();
1162
1163    #[inline]
1164    fn try_from(bytes: Bytes) -> Result<Self, Self::Error> {
1165        if bytes.len() != Self::SIZE {
1166            return Err(());
1167        }
1168
1169        Ok(Self(CowBytes::Shared(bytes)))
1170    }
1171}
1172
1173impl TryFrom<BytesMut> for Piece {
1174    type Error = ();
1175
1176    #[inline]
1177    fn try_from(bytes: BytesMut) -> Result<Self, Self::Error> {
1178        if bytes.len() != Self::SIZE {
1179            return Err(());
1180        }
1181
1182        Ok(Self(CowBytes::Owned(bytes)))
1183    }
1184}
1185
1186impl From<&PieceArray> for Piece {
1187    #[inline]
1188    fn from(value: &PieceArray) -> Self {
1189        Self(CowBytes::Shared(Bytes::copy_from_slice(value.as_ref())))
1190    }
1191}
1192
1193impl Deref for Piece {
1194    type Target = PieceArray;
1195
1196    #[inline]
1197    fn deref(&self) -> &Self::Target {
1198        <&[u8; Self::SIZE]>::try_from(self.as_ref())
1199            .expect("Slice of memory has correct length; qed")
1200            .into()
1201    }
1202}
1203
1204impl DerefMut for Piece {
1205    #[inline]
1206    fn deref_mut(&mut self) -> &mut Self::Target {
1207        <&mut [u8; Self::SIZE]>::try_from(self.as_mut())
1208            .expect("Slice of memory has correct length; qed")
1209            .into()
1210    }
1211}
1212
1213impl AsRef<[u8]> for Piece {
1214    #[inline]
1215    fn as_ref(&self) -> &[u8] {
1216        self.0.as_ref()
1217    }
1218}
1219
1220impl AsMut<[u8]> for Piece {
1221    #[inline]
1222    fn as_mut(&mut self) -> &mut [u8] {
1223        self.0.as_mut()
1224    }
1225}
1226
1227impl Piece {
1228    /// Size of a piece (in bytes).
1229    pub const SIZE: usize = Record::SIZE + RecordCommitment::SIZE + RecordWitness::SIZE;
1230
1231    /// Ensure piece contains cheaply cloneable shared data.
1232    ///
1233    /// Internally piece uses CoW mechanism and can store either mutable owned data or data that is
1234    /// cheap to clone, calling this method will ensure further clones will not result in additional
1235    /// memory allocations.
1236    pub fn to_shared(self) -> Self {
1237        Self(match self.0 {
1238            CowBytes::Shared(bytes) => CowBytes::Shared(bytes),
1239            CowBytes::Owned(bytes) => CowBytes::Shared(bytes.freeze()),
1240        })
1241    }
1242}
1243
1244/// A piece of archival history in Subspace Network.
1245///
1246/// This version is allocated on the stack, for heap-allocated piece see [`Piece`].
1247///
1248/// Internally piece contains a record and corresponding witness that together with segment
1249/// commitment of the segment this piece belongs to can be used to verify that a piece belongs to
1250/// the actual archival history of the blockchain.
1251#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deref, DerefMut, AsRef, AsMut)]
1252#[repr(transparent)]
1253pub struct PieceArray([u8; Piece::SIZE]);
1254
1255impl fmt::Debug for PieceArray {
1256    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1257        write!(f, "{}", hex::encode(self.0))
1258    }
1259}
1260
1261impl Default for PieceArray {
1262    #[inline]
1263    fn default() -> Self {
1264        Self([0u8; Piece::SIZE])
1265    }
1266}
1267
1268impl AsRef<[u8]> for PieceArray {
1269    #[inline]
1270    fn as_ref(&self) -> &[u8] {
1271        &self.0
1272    }
1273}
1274
1275impl AsMut<[u8]> for PieceArray {
1276    #[inline]
1277    fn as_mut(&mut self) -> &mut [u8] {
1278        &mut self.0
1279    }
1280}
1281
1282impl From<&PieceArray> for &[u8; Piece::SIZE] {
1283    #[inline]
1284    fn from(value: &PieceArray) -> Self {
1285        // SAFETY: `PieceArray` is `#[repr(transparent)]` and guaranteed to have the same memory
1286        // layout
1287        unsafe { mem::transmute(value) }
1288    }
1289}
1290
1291impl From<&[u8; Piece::SIZE]> for &PieceArray {
1292    #[inline]
1293    fn from(value: &[u8; Piece::SIZE]) -> Self {
1294        // SAFETY: `PieceArray` is `#[repr(transparent)]` and guaranteed to have the same memory
1295        // layout
1296        unsafe { mem::transmute(value) }
1297    }
1298}
1299
1300impl From<&mut PieceArray> for &mut [u8; Piece::SIZE] {
1301    #[inline]
1302    fn from(value: &mut PieceArray) -> Self {
1303        // SAFETY: `PieceArray` is `#[repr(transparent)]` and guaranteed to have the same memory
1304        // layout
1305        unsafe { mem::transmute(value) }
1306    }
1307}
1308
1309impl From<&mut [u8; Piece::SIZE]> for &mut PieceArray {
1310    #[inline]
1311    fn from(value: &mut [u8; Piece::SIZE]) -> Self {
1312        // SAFETY: `PieceArray` is `#[repr(transparent)]` and guaranteed to have the same memory
1313        // layout
1314        unsafe { mem::transmute(value) }
1315    }
1316}
1317
1318impl PieceArray {
1319    /// Create boxed value without hitting stack overflow
1320    #[inline]
1321    pub fn new_boxed() -> Box<Self> {
1322        // TODO: Should have been just `::new()`, but https://github.com/rust-lang/rust/issues/53827
1323        // SAFETY: Data structure filled with zeroes is a valid invariant
1324        unsafe { Box::<Self>::new_zeroed().assume_init() }
1325    }
1326
1327    /// Split piece into underlying components.
1328    #[inline]
1329    pub fn split(&self) -> (&Record, &RecordCommitment, &RecordWitness) {
1330        let (record, extra) = self.0.split_at(Record::SIZE);
1331        let (commitment, witness) = extra.split_at(RecordCommitment::SIZE);
1332
1333        let record = <&[u8; Record::SIZE]>::try_from(record)
1334            .expect("Slice of memory has correct length; qed");
1335        let commitment = <&[u8; RecordCommitment::SIZE]>::try_from(commitment)
1336            .expect("Slice of memory has correct length; qed");
1337        let witness = <&[u8; RecordWitness::SIZE]>::try_from(witness)
1338            .expect("Slice of memory has correct length; qed");
1339
1340        (record.into(), commitment.into(), witness.into())
1341    }
1342
1343    /// Split piece into underlying mutable components.
1344    #[inline]
1345    pub fn split_mut(&mut self) -> (&mut Record, &mut RecordCommitment, &mut RecordWitness) {
1346        let (record, extra) = self.0.split_at_mut(Record::SIZE);
1347        let (commitment, witness) = extra.split_at_mut(RecordCommitment::SIZE);
1348
1349        let record = <&mut [u8; Record::SIZE]>::try_from(record)
1350            .expect("Slice of memory has correct length; qed");
1351        let commitment = <&mut [u8; RecordCommitment::SIZE]>::try_from(commitment)
1352            .expect("Slice of memory has correct length; qed");
1353        let witness = <&mut [u8; RecordWitness::SIZE]>::try_from(witness)
1354            .expect("Slice of memory has correct length; qed");
1355
1356        (record.into(), commitment.into(), witness.into())
1357    }
1358
1359    /// Record contained within a piece.
1360    #[inline]
1361    pub fn record(&self) -> &Record {
1362        self.split().0
1363    }
1364
1365    /// Mutable record contained within a piece.
1366    #[inline]
1367    pub fn record_mut(&mut self) -> &mut Record {
1368        self.split_mut().0
1369    }
1370
1371    /// Commitment contained within a piece.
1372    #[inline]
1373    pub fn commitment(&self) -> &RecordCommitment {
1374        self.split().1
1375    }
1376
1377    /// Mutable commitment contained within a piece.
1378    #[inline]
1379    pub fn commitment_mut(&mut self) -> &mut RecordCommitment {
1380        self.split_mut().1
1381    }
1382
1383    /// Witness contained within a piece.
1384    #[inline]
1385    pub fn witness(&self) -> &RecordWitness {
1386        self.split().2
1387    }
1388
1389    /// Mutable witness contained within a piece.
1390    #[inline]
1391    pub fn witness_mut(&mut self) -> &mut RecordWitness {
1392        self.split_mut().2
1393    }
1394
1395    /// Convenient conversion from slice of piece array to underlying representation for efficiency
1396    /// purposes.
1397    #[inline]
1398    pub fn slice_to_repr(value: &[Self]) -> &[[u8; Piece::SIZE]] {
1399        // SAFETY: `PieceArray` is `#[repr(transparent)]` and guaranteed to have the same memory
1400        // layout
1401        unsafe { mem::transmute(value) }
1402    }
1403
1404    /// Convenient conversion from slice of underlying representation to piece array for efficiency
1405    /// purposes.
1406    #[inline]
1407    pub fn slice_from_repr(value: &[[u8; Piece::SIZE]]) -> &[Self] {
1408        // SAFETY: `PieceArray` is `#[repr(transparent)]` and guaranteed to have the same memory
1409        // layout
1410        unsafe { mem::transmute(value) }
1411    }
1412
1413    /// Convenient conversion from mutable slice of piece array to underlying representation for
1414    /// efficiency purposes.
1415    #[inline]
1416    pub fn slice_mut_to_repr(value: &mut [Self]) -> &mut [[u8; Piece::SIZE]] {
1417        // SAFETY: `PieceArray` is `#[repr(transparent)]` and guaranteed to have the same memory
1418        // layout
1419        unsafe { mem::transmute(value) }
1420    }
1421
1422    /// Convenient conversion from mutable slice of underlying representation to piece array for
1423    /// efficiency purposes.
1424    #[inline]
1425    pub fn slice_mut_from_repr(value: &mut [[u8; Piece::SIZE]]) -> &mut [Self] {
1426        // SAFETY: `PieceArray` is `#[repr(transparent)]` and guaranteed to have the same memory
1427        // layout
1428        unsafe { mem::transmute(value) }
1429    }
1430}
1431
1432impl From<Box<PieceArray>> for Vec<u8> {
1433    fn from(value: Box<PieceArray>) -> Self {
1434        let mut value = mem::ManuallyDrop::new(value);
1435        // SAFETY: Always contains fixed allocation of bytes
1436        unsafe { Vec::from_raw_parts(value.as_mut_ptr(), Piece::SIZE, Piece::SIZE) }
1437    }
1438}
1439
1440/// Flat representation of multiple pieces concatenated for more efficient for processing
1441#[derive(Clone, PartialEq, Eq)]
1442pub struct FlatPieces(CowBytes);
1443
1444impl fmt::Debug for FlatPieces {
1445    #[inline]
1446    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1447        f.debug_struct("FlatPieces").finish_non_exhaustive()
1448    }
1449}
1450
1451impl Deref for FlatPieces {
1452    type Target = [PieceArray];
1453
1454    #[inline]
1455    fn deref(&self) -> &Self::Target {
1456        let bytes = self.0.as_ref();
1457        // SAFETY: Bytes slice has length of multiples of piece size and lifetimes of returned data
1458        // are preserved
1459        let pieces = unsafe {
1460            slice::from_raw_parts(
1461                bytes.as_ptr() as *const [u8; Piece::SIZE],
1462                bytes.len() / Piece::SIZE,
1463            )
1464        };
1465        PieceArray::slice_from_repr(pieces)
1466    }
1467}
1468
1469impl DerefMut for FlatPieces {
1470    #[inline]
1471    fn deref_mut(&mut self) -> &mut Self::Target {
1472        let bytes = self.0.as_mut();
1473        // SAFETY: Bytes slice has length of multiples of piece size and lifetimes of returned data
1474        // are preserved
1475        let pieces = unsafe {
1476            slice::from_raw_parts_mut(
1477                bytes.as_mut_ptr() as *mut [u8; Piece::SIZE],
1478                bytes.len() / Piece::SIZE,
1479            )
1480        };
1481        PieceArray::slice_mut_from_repr(pieces)
1482    }
1483}
1484
1485impl FlatPieces {
1486    /// Allocate `FlatPieces` that will hold `piece_count` pieces filled with zeroes
1487    #[inline]
1488    pub fn new(piece_count: usize) -> Self {
1489        Self(CowBytes::Owned(BytesMut::zeroed(piece_count * Piece::SIZE)))
1490    }
1491
1492    /// Iterate over all pieces.
1493    ///
1494    /// NOTE: Unless [`Self::to_shared`] was called first, iterator may have to allocate each piece
1495    /// from scratch, which is rarely a desired behavior.
1496    #[inline]
1497    pub fn pieces(&self) -> Box<dyn ExactSizeIterator<Item = Piece> + '_> {
1498        match &self.0 {
1499            CowBytes::Shared(bytes) => Box::new(
1500                bytes
1501                    .as_chunks::<{ Piece::SIZE }>()
1502                    .0
1503                    .iter()
1504                    .map(|slice| Piece(CowBytes::Shared(bytes.slice_ref(slice)))),
1505            ),
1506            CowBytes::Owned(bytes) => Box::new(
1507                bytes
1508                    .as_chunks::<{ Piece::SIZE }>()
1509                    .0
1510                    .iter()
1511                    .map(|slice| Piece(CowBytes::Shared(Bytes::copy_from_slice(slice)))),
1512            ),
1513        }
1514    }
1515
1516    /// Iterator over source pieces (even indices)
1517    #[inline]
1518    pub fn source_pieces(&self) -> impl ExactSizeIterator<Item = Piece> + '_ {
1519        self.pieces().step_by(2)
1520    }
1521
1522    /// Iterator over source pieces (even indices)
1523    #[inline]
1524    pub fn source(&self) -> impl ExactSizeIterator<Item = &'_ PieceArray> + '_ {
1525        self.iter().step_by(2)
1526    }
1527
1528    /// Mutable iterator over source pieces (even indices)
1529    #[inline]
1530    pub fn source_mut(&mut self) -> impl ExactSizeIterator<Item = &'_ mut PieceArray> + '_ {
1531        self.iter_mut().step_by(2)
1532    }
1533
1534    /// Iterator over parity pieces (odd indices)
1535    #[inline]
1536    pub fn parity_pieces(&self) -> impl ExactSizeIterator<Item = Piece> + '_ {
1537        self.pieces().skip(1).step_by(2)
1538    }
1539
1540    /// Iterator over parity pieces (odd indices)
1541    #[inline]
1542    pub fn parity(&self) -> impl ExactSizeIterator<Item = &'_ PieceArray> + '_ {
1543        self.iter().skip(1).step_by(2)
1544    }
1545
1546    /// Mutable iterator over parity pieces (odd indices)
1547    #[inline]
1548    pub fn parity_mut(&mut self) -> impl ExactSizeIterator<Item = &'_ mut PieceArray> + '_ {
1549        self.iter_mut().skip(1).step_by(2)
1550    }
1551
1552    /// Ensure flat pieces contains cheaply cloneable shared data.
1553    ///
1554    /// Internally flat pieces uses CoW mechanism and can store either mutable owned data or data
1555    /// that is cheap to clone, calling this method will ensure further clones and returned pieces
1556    /// will not result in additional memory allocations.
1557    pub fn to_shared(self) -> Self {
1558        Self(match self.0 {
1559            CowBytes::Shared(bytes) => CowBytes::Shared(bytes),
1560            CowBytes::Owned(bytes) => CowBytes::Shared(bytes.freeze()),
1561        })
1562    }
1563}
1564
1565#[cfg(feature = "parallel")]
1566impl FlatPieces {
1567    /// Parallel iterator over source pieces (even indices)
1568    #[inline]
1569    pub fn par_source(&self) -> impl IndexedParallelIterator<Item = &'_ PieceArray> + '_ {
1570        self.par_iter().step_by(2)
1571    }
1572
1573    /// Mutable parallel iterator over source pieces (even indices)
1574    #[inline]
1575    pub fn par_source_mut(
1576        &mut self,
1577    ) -> impl IndexedParallelIterator<Item = &'_ mut PieceArray> + '_ {
1578        self.par_iter_mut().step_by(2)
1579    }
1580
1581    /// Parallel iterator over parity pieces (odd indices)
1582    #[inline]
1583    pub fn par_parity(&self) -> impl IndexedParallelIterator<Item = &'_ PieceArray> + '_ {
1584        self.par_iter().skip(1).step_by(2)
1585    }
1586
1587    /// Mutable parallel iterator over parity pieces (odd indices)
1588    #[inline]
1589    pub fn par_parity_mut(
1590        &mut self,
1591    ) -> impl IndexedParallelIterator<Item = &'_ mut PieceArray> + '_ {
1592        self.par_iter_mut().skip(1).step_by(2)
1593    }
1594}