1#[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#[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 pub const SIZE: usize = mem::size_of::<u64>();
112 pub const ZERO: PieceIndex = PieceIndex(0);
114 pub const ONE: PieceIndex = PieceIndex(1);
116
117 #[inline]
119 pub const fn new(n: u64) -> Self {
120 Self(n)
121 }
122
123 #[inline]
125 pub const fn from_bytes(bytes: [u8; Self::SIZE]) -> Self {
126 Self(u64::from_le_bytes(bytes))
127 }
128
129 #[inline]
131 pub const fn to_bytes(self) -> [u8; Self::SIZE] {
132 self.0.to_le_bytes()
133 }
134
135 #[inline]
137 pub const fn segment_index(&self) -> SegmentIndex {
138 SegmentIndex::new(self.0 / ArchivedHistorySegment::NUM_PIECES as u64)
139 }
140
141 #[inline]
143 pub const fn position(&self) -> u32 {
144 (self.0 % ArchivedHistorySegment::NUM_PIECES as u64) as u32
146 }
147
148 #[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 #[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 #[inline]
178 pub const fn is_source(&self) -> bool {
179 self.0 % (RecordedHistorySegment::ERASURE_CODING_RATE.1 as u64)
181 < (RecordedHistorySegment::ERASURE_CODING_RATE.0 as u64)
182 }
183
184 #[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 #[inline]
194 pub const fn prev_source_index(&self) -> Option<PieceIndex> {
195 if self.source_position() == 0 {
196 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#[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 pub const ZERO: PieceOffset = PieceOffset(0);
310 pub const ONE: PieceOffset = PieceOffset(1);
312
313 #[inline]
315 pub const fn to_bytes(self) -> [u8; mem::size_of::<u16>()] {
316 self.0.to_le_bytes()
317 }
318}
319
320#[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 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 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 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 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 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 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 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 unsafe { mem::transmute(value) }
423 }
424}
425
426impl RawRecord {
427 pub const NUM_CHUNKS: usize = 2_usize.pow(15);
429 pub const SIZE: usize = ScalarBytes::SAFE_BYTES * Self::NUM_CHUNKS;
431
432 #[inline]
434 pub fn new_boxed() -> Box<Self> {
435 unsafe { Box::new_zeroed().assume_init() }
438 }
439
440 #[inline]
443 pub fn slice_to_repr(value: &[Self]) -> &[[[u8; ScalarBytes::SAFE_BYTES]; Self::NUM_CHUNKS]] {
444 unsafe { mem::transmute(value) }
447 }
448
449 #[inline]
452 pub fn slice_from_repr(value: &[[[u8; ScalarBytes::SAFE_BYTES]; Self::NUM_CHUNKS]]) -> &[Self] {
453 unsafe { mem::transmute(value) }
456 }
457
458 #[inline]
461 pub fn slice_mut_to_repr(
462 value: &mut [Self],
463 ) -> &mut [[[u8; ScalarBytes::SAFE_BYTES]; Self::NUM_CHUNKS]] {
464 unsafe { mem::transmute(value) }
467 }
468
469 #[inline]
472 pub fn slice_mut_from_repr(
473 value: &mut [[[u8; ScalarBytes::SAFE_BYTES]; Self::NUM_CHUNKS]],
474 ) -> &mut [Self] {
475 unsafe { mem::transmute(value) }
478 }
479}
480
481#[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 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 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 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 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 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 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 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 unsafe { mem::transmute(value) }
580 }
581}
582
583impl Record {
584 pub const NUM_CHUNKS: usize = RawRecord::NUM_CHUNKS;
586 pub const NUM_S_BUCKETS: usize = Self::NUM_CHUNKS
590 * RecordedHistorySegment::ERASURE_CODING_RATE.1
591 / RecordedHistorySegment::ERASURE_CODING_RATE.0;
592 pub const SIZE: usize = ScalarBytes::FULL_BYTES * Self::NUM_CHUNKS;
595
596 #[inline]
598 pub fn new_boxed() -> Box<Self> {
599 unsafe { Box::new_zeroed().assume_init() }
602 }
603
604 #[inline]
606 pub fn new_zero_vec(length: usize) -> Vec<Self> {
607 unsafe { Box::<[Self]>::new_zeroed_slice(length).assume_init() }.into_vec()
610 }
611
612 #[inline]
615 pub fn slice_to_repr(value: &[Self]) -> &[[[u8; ScalarBytes::FULL_BYTES]; Self::NUM_CHUNKS]] {
616 unsafe { mem::transmute(value) }
618 }
619
620 #[inline]
623 pub fn slice_from_repr(value: &[[[u8; ScalarBytes::FULL_BYTES]; Self::NUM_CHUNKS]]) -> &[Self] {
624 unsafe { mem::transmute(value) }
626 }
627
628 #[inline]
631 pub fn slice_mut_to_repr(
632 value: &mut [Self],
633 ) -> &mut [[[u8; ScalarBytes::FULL_BYTES]; Self::NUM_CHUNKS]] {
634 unsafe { mem::transmute(value) }
636 }
637
638 #[inline]
641 pub fn slice_mut_from_repr(
642 value: &mut [[[u8; ScalarBytes::FULL_BYTES]; Self::NUM_CHUNKS]],
643 ) -> &mut [Self] {
644 unsafe { mem::transmute(value) }
646 }
647
648 #[inline]
651 pub fn to_raw_record_chunks(
652 &self,
653 ) -> impl DoubleEndedIterator<Item = &'_ [u8; ScalarBytes::SAFE_BYTES]> + '_ {
654 self.iter()
657 .map(|bytes| bytes[1..].try_into().expect("Correct length; qed"))
658 }
659
660 #[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#[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 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 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 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 unsafe { mem::transmute(value) }
799 }
800}
801
802impl RecordCommitment {
803 pub const SIZE: usize = 48;
805}
806
807#[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 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 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 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 unsafe { mem::transmute(value) }
935 }
936}
937
938impl RecordWitness {
939 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 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#[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 pub const SIZE: usize = Record::SIZE + RecordCommitment::SIZE + RecordWitness::SIZE;
1230
1231 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#[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 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 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 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 unsafe { mem::transmute(value) }
1315 }
1316}
1317
1318impl PieceArray {
1319 #[inline]
1321 pub fn new_boxed() -> Box<Self> {
1322 unsafe { Box::<Self>::new_zeroed().assume_init() }
1325 }
1326
1327 #[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 #[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 #[inline]
1361 pub fn record(&self) -> &Record {
1362 self.split().0
1363 }
1364
1365 #[inline]
1367 pub fn record_mut(&mut self) -> &mut Record {
1368 self.split_mut().0
1369 }
1370
1371 #[inline]
1373 pub fn commitment(&self) -> &RecordCommitment {
1374 self.split().1
1375 }
1376
1377 #[inline]
1379 pub fn commitment_mut(&mut self) -> &mut RecordCommitment {
1380 self.split_mut().1
1381 }
1382
1383 #[inline]
1385 pub fn witness(&self) -> &RecordWitness {
1386 self.split().2
1387 }
1388
1389 #[inline]
1391 pub fn witness_mut(&mut self) -> &mut RecordWitness {
1392 self.split_mut().2
1393 }
1394
1395 #[inline]
1398 pub fn slice_to_repr(value: &[Self]) -> &[[u8; Piece::SIZE]] {
1399 unsafe { mem::transmute(value) }
1402 }
1403
1404 #[inline]
1407 pub fn slice_from_repr(value: &[[u8; Piece::SIZE]]) -> &[Self] {
1408 unsafe { mem::transmute(value) }
1411 }
1412
1413 #[inline]
1416 pub fn slice_mut_to_repr(value: &mut [Self]) -> &mut [[u8; Piece::SIZE]] {
1417 unsafe { mem::transmute(value) }
1420 }
1421
1422 #[inline]
1425 pub fn slice_mut_from_repr(value: &mut [[u8; Piece::SIZE]]) -> &mut [Self] {
1426 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 unsafe { Vec::from_raw_parts(value.as_mut_ptr(), Piece::SIZE, Piece::SIZE) }
1437 }
1438}
1439
1440#[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 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 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 #[inline]
1488 pub fn new(piece_count: usize) -> Self {
1489 Self(CowBytes::Owned(BytesMut::zeroed(piece_count * Piece::SIZE)))
1490 }
1491
1492 #[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 #[inline]
1518 pub fn source_pieces(&self) -> impl ExactSizeIterator<Item = Piece> + '_ {
1519 self.pieces().step_by(2)
1520 }
1521
1522 #[inline]
1524 pub fn source(&self) -> impl ExactSizeIterator<Item = &'_ PieceArray> + '_ {
1525 self.iter().step_by(2)
1526 }
1527
1528 #[inline]
1530 pub fn source_mut(&mut self) -> impl ExactSizeIterator<Item = &'_ mut PieceArray> + '_ {
1531 self.iter_mut().step_by(2)
1532 }
1533
1534 #[inline]
1536 pub fn parity_pieces(&self) -> impl ExactSizeIterator<Item = Piece> + '_ {
1537 self.pieces().skip(1).step_by(2)
1538 }
1539
1540 #[inline]
1542 pub fn parity(&self) -> impl ExactSizeIterator<Item = &'_ PieceArray> + '_ {
1543 self.iter().skip(1).step_by(2)
1544 }
1545
1546 #[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 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 #[inline]
1569 pub fn par_source(&self) -> impl IndexedParallelIterator<Item = &'_ PieceArray> + '_ {
1570 self.par_iter().step_by(2)
1571 }
1572
1573 #[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 #[inline]
1583 pub fn par_parity(&self) -> impl IndexedParallelIterator<Item = &'_ PieceArray> + '_ {
1584 self.par_iter().skip(1).step_by(2)
1585 }
1586
1587 #[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}