Skip to main content

ab_core_primitives/pieces/
flat_pieces.rs

1use crate::pieces::{InnerPiece, Piece};
2use crate::segments::RecordedHistorySegment;
3use ab_aligned_buffer::{OwnedAlignedBuffer, SharedAlignedBuffer};
4use ab_io_type::trivial_type::TrivialType;
5use alloc::boxed::Box;
6use core::fmt;
7use core::ops::{Deref, DerefMut};
8#[cfg(feature = "parallel")]
9use rayon::prelude::*;
10
11/// Buffer that is either owned and mutable or shared and cheap to clone
12#[derive(Clone)]
13enum CowBuffer {
14    Owned(OwnedAlignedBuffer),
15    Shared(SharedAlignedBuffer),
16}
17
18impl CowBuffer {
19    #[inline(always)]
20    fn as_slice(&self) -> &[u8] {
21        match self {
22            Self::Owned(buffer) => buffer.as_slice(),
23            Self::Shared(buffer) => buffer.as_slice(),
24        }
25    }
26
27    /// Shared buffer is copied into a new allocation first, unless it is the last reference to
28    /// its allocation
29    #[inline(always)]
30    fn as_mut_slice(&mut self) -> &mut [u8] {
31        match self {
32            Self::Owned(buffer) => buffer.as_mut_slice(),
33            Self::Shared(buffer) => buffer.make_mut(),
34        }
35    }
36}
37
38/// Flat representation of multiple pieces concatenated for more efficient for processing
39#[derive(Clone)]
40pub struct FlatPieces(CowBuffer);
41
42impl PartialEq for FlatPieces {
43    #[inline]
44    fn eq(&self, other: &Self) -> bool {
45        self.0.as_slice() == other.0.as_slice()
46    }
47}
48
49impl Eq for FlatPieces {}
50
51impl fmt::Debug for FlatPieces {
52    #[inline]
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        f.debug_struct("FlatPieces").finish_non_exhaustive()
55    }
56}
57
58impl Deref for FlatPieces {
59    type Target = [InnerPiece];
60
61    #[inline]
62    fn deref(&self) -> &Self::Target {
63        let bytes = self.0.as_slice();
64        let (pieces, _) = InnerPiece::slice_from_bytes(bytes, bytes.len() / Piece::SIZE).expect(
65            "`InnerPiece` has alignment of 1 and `bytes` are at least this many pieces long; qed",
66        );
67        pieces
68    }
69}
70
71impl DerefMut for FlatPieces {
72    #[inline]
73    fn deref_mut(&mut self) -> &mut Self::Target {
74        let bytes = self.0.as_mut_slice();
75        let num_pieces = bytes.len() / Piece::SIZE;
76        let (pieces, _) = InnerPiece::slice_from_bytes_mut(bytes, num_pieces).expect(
77            "`InnerPiece` has alignment of 1 and `bytes` are at least this many pieces long; qed",
78        );
79        pieces
80    }
81}
82
83impl FlatPieces {
84    /// Allocate `FlatPieces` that will hold `piece_count` pieces filled with zeroes.
85    ///
86    /// # Panics
87    /// If pieces don't fit into [`OwnedAlignedBuffer::MAX_CAPACITY`]
88    #[inline]
89    pub fn new(piece_count: usize) -> Self {
90        let size = piece_count
91            .checked_mul(Piece::SIZE)
92            .and_then(|size| u32::try_from(size).ok())
93            .unwrap_or_else(|| panic!("{piece_count} pieces don't fit into a buffer"));
94
95        Self(CowBuffer::Owned(OwnedAlignedBuffer::zeroed(size)))
96    }
97
98    /// Iterate over all pieces.
99    ///
100    /// NOTE: [`Piece`] returned by iterator is sharing memory with the original [`FlatPieces`]
101    /// allocation, which is cheap, but may result in additional memory usage if the piece is kept
102    /// around for a long time. But it only happens if [`Self::to_shared`] was called first,
103    /// otherwise iterator may have to allocate each piece from scratch, which is rarely a
104    /// desired behavior.
105    #[inline]
106    pub fn pieces(&self) -> Box<dyn ExactSizeIterator<Item = Piece> + '_> {
107        match &self.0 {
108            CowBuffer::Shared(buffer) => {
109                Box::new((0..buffer.len()).step_by(Piece::SIZE).map(|start| {
110                    Piece(
111                        buffer
112                            .get_slice(start..start + Piece::SIZE_U32)
113                            .expect("Buffer contains whole pieces; qed"),
114                    )
115                }))
116            }
117            CowBuffer::Owned(buffer) => Box::new(
118                buffer
119                    .as_chunks::<{ Piece::SIZE }>()
120                    .0
121                    .iter()
122                    .map(|bytes| Piece(SharedAlignedBuffer::from_bytes(bytes))),
123            ),
124        }
125    }
126
127    /// Iterator over source pieces (even indices)
128    #[inline]
129    pub fn source_pieces(&self) -> impl ExactSizeIterator<Item = Piece> + '_ {
130        self.pieces().take(RecordedHistorySegment::NUM_RAW_RECORDS)
131    }
132
133    /// Iterator over source pieces (even indices)
134    #[inline]
135    pub fn source(&self) -> impl ExactSizeIterator<Item = &'_ InnerPiece> + '_ {
136        self.iter().take(RecordedHistorySegment::NUM_RAW_RECORDS)
137    }
138
139    /// Mutable iterator over source pieces (even indices)
140    #[inline]
141    pub fn source_mut(&mut self) -> impl ExactSizeIterator<Item = &'_ mut InnerPiece> + '_ {
142        self.iter_mut()
143            .take(RecordedHistorySegment::NUM_RAW_RECORDS)
144    }
145
146    /// Iterator over parity pieces (odd indices)
147    #[inline]
148    pub fn parity_pieces(&self) -> impl ExactSizeIterator<Item = Piece> + '_ {
149        self.pieces().skip(RecordedHistorySegment::NUM_RAW_RECORDS)
150    }
151
152    /// Iterator over parity pieces (odd indices)
153    #[inline]
154    pub fn parity(&self) -> impl ExactSizeIterator<Item = &'_ InnerPiece> + '_ {
155        self.iter().skip(RecordedHistorySegment::NUM_RAW_RECORDS)
156    }
157
158    /// Mutable iterator over parity pieces (odd indices)
159    #[inline]
160    pub fn parity_mut(&mut self) -> impl ExactSizeIterator<Item = &'_ mut InnerPiece> + '_ {
161        self.iter_mut()
162            .skip(RecordedHistorySegment::NUM_RAW_RECORDS)
163    }
164
165    /// Ensure flat pieces contains cheaply cloneable shared data.
166    ///
167    /// Internally flat pieces uses CoW mechanism and can store either mutable owned data or data
168    /// that is cheap to clone, calling this method will ensure further clones and returned pieces
169    /// will not result in additional memory allocations.
170    pub fn to_shared(self) -> Self {
171        Self(match self.0 {
172            CowBuffer::Shared(buffer) => CowBuffer::Shared(buffer),
173            CowBuffer::Owned(buffer) => CowBuffer::Shared(buffer.into_shared()),
174        })
175    }
176
177    /// Parallel iterator over source pieces (even indices)
178    #[inline]
179    #[cfg(feature = "parallel")]
180    pub fn par_source(&self) -> impl IndexedParallelIterator<Item = &'_ InnerPiece> + '_ {
181        self.par_iter()
182            .take(RecordedHistorySegment::NUM_RAW_RECORDS)
183    }
184
185    /// Mutable parallel iterator over source pieces (even indices)
186    #[inline]
187    #[cfg(feature = "parallel")]
188    pub fn par_source_mut(
189        &mut self,
190    ) -> impl IndexedParallelIterator<Item = &'_ mut InnerPiece> + '_ {
191        self.par_iter_mut()
192            .take(RecordedHistorySegment::NUM_RAW_RECORDS)
193    }
194
195    /// Parallel iterator over parity pieces (odd indices)
196    #[inline]
197    #[cfg(feature = "parallel")]
198    pub fn par_parity(&self) -> impl IndexedParallelIterator<Item = &'_ InnerPiece> + '_ {
199        self.par_iter()
200            .skip(RecordedHistorySegment::NUM_RAW_RECORDS)
201    }
202
203    /// Mutable parallel iterator over parity pieces (odd indices)
204    #[inline]
205    #[cfg(feature = "parallel")]
206    pub fn par_parity_mut(
207        &mut self,
208    ) -> impl IndexedParallelIterator<Item = &'_ mut InnerPiece> + '_ {
209        self.par_iter_mut()
210            .skip(RecordedHistorySegment::NUM_RAW_RECORDS)
211    }
212}