object_rainbow/
lib.rs

1#![deny(unsafe_code)]
2
3extern crate self as object_rainbow;
4
5use std::{
6    any::{Any, TypeId},
7    cell::Cell,
8    convert::Infallible,
9    future::ready,
10    marker::PhantomData,
11    ops::{Deref, DerefMut},
12    pin::Pin,
13    sync::Arc,
14};
15
16pub use anyhow::anyhow;
17use generic_array::{ArrayLength, GenericArray};
18pub use object_rainbow_derive::{
19    Enum, InlineOutput, ListHashes, MaybeHasNiche, Parse, ParseAsInline, ParseInline, Size, Tagged,
20    ToOutput, Topological,
21};
22use sha2::{Digest, Sha256};
23#[doc(hidden)]
24pub use typenum;
25use typenum::Unsigned;
26
27pub use self::enumkind::Enum;
28pub use self::error::{Error, Result};
29pub use self::hash::{Hash, OptionalHash};
30pub use self::niche::{
31    AutoEnumNiche, AutoNiche, HackNiche, MaybeHasNiche, Niche, NicheForUnsized, NoNiche, OneNiche,
32    SomeNiche, ZeroNiche, ZeroNoNiche,
33};
34#[doc(hidden)]
35pub use self::niche::{MaybeNiche, MnArray, NicheFoldOrArray, NicheOr};
36
37pub mod enumkind;
38mod error;
39mod hash;
40pub mod hashed;
41mod impls;
42pub mod length_prefixed;
43mod niche;
44pub mod numeric;
45mod sha2_const;
46pub mod zero_terminated;
47
48/// SHA-256 hash size in bytes.
49pub const HASH_SIZE: usize = sha2_const::Sha256::DIGEST_SIZE;
50
51/// Address within a [`PointInput`].
52///
53/// This was introduced:
54/// - to avoid using a [`Hash`]-only map
55/// - to differentiate between separate [`Hash`]es within a context
56#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ParseAsInline)]
57pub struct Address {
58    /// Monotonically incremented index. This is not present at all in the actual format.
59    pub index: usize,
60    /// Only this part is part of the parsed/generated input.
61    pub hash: Hash,
62}
63
64impl Address {
65    /// Construct an address which is invalid within parsing context, but can be used in map-based
66    /// [`Resolve`]s.
67    pub fn from_hash(hash: Hash) -> Self {
68        Self {
69            index: usize::MAX,
70            hash,
71        }
72    }
73}
74
75impl<I: PointInput> ParseInline<I> for Address {
76    fn parse_inline(input: &mut I) -> crate::Result<Self> {
77        Ok(Self {
78            index: input.next_index(),
79            hash: input.parse_inline()?,
80        })
81    }
82}
83
84/// Fallible future type yielding either `T` or [`Error`].
85pub type FailFuture<'a, T> = Pin<Box<dyn 'a + Send + Future<Output = Result<T>>>>;
86
87pub type Node<T> = (T, Arc<dyn Resolve>);
88
89/// Returned by [`Resolve`] and [`FetchBytes`]. Represents traversal through the object graph.
90pub type ByteNode = Node<Vec<u8>>;
91
92/// Trait for contextually using [`Any`]. Can itself be implemented for non-`'static` and `?Sized`
93/// types, and is `dyn`-compatible.
94pub trait AsAny {
95    /// Get a shared RTTI reference.
96    fn any_ref(&self) -> &dyn Any
97    where
98        Self: 'static;
99    /// Get an exclusive RTTI reference.
100    fn any_mut(&mut self) -> &mut dyn Any
101    where
102        Self: 'static;
103    /// Get an RTTI [`Box`].
104    fn any_box(self: Box<Self>) -> Box<dyn Any>
105    where
106        Self: 'static;
107    /// Get an RTTI [`Arc`].
108    fn any_arc(self: Arc<Self>) -> Arc<dyn Any>
109    where
110        Self: 'static;
111    /// Get an RTTI [`Arc`] which is also [`Send`].
112    fn any_arc_sync(self: Arc<Self>) -> Arc<dyn Send + Sync + Any>
113    where
114        Self: 'static + Send + Sync;
115}
116
117impl<T> AsAny for T {
118    fn any_ref(&self) -> &dyn Any
119    where
120        Self: 'static,
121    {
122        self
123    }
124
125    fn any_mut(&mut self) -> &mut dyn Any
126    where
127        Self: 'static,
128    {
129        self
130    }
131
132    fn any_box(self: Box<Self>) -> Box<dyn Any>
133    where
134        Self: 'static,
135    {
136        self
137    }
138
139    fn any_arc(self: Arc<Self>) -> Arc<dyn Any>
140    where
141        Self: 'static,
142    {
143        self
144    }
145
146    fn any_arc_sync(self: Arc<Self>) -> Arc<dyn Send + Sync + Any>
147    where
148        Self: 'static + Send + Sync,
149    {
150        self
151    }
152}
153
154/// Something that resolve [`Address`]es to [`ByteNode`]s.
155pub trait Resolve: Send + Sync + AsAny {
156    /// Resolve the address. For an [`Object`], this is what gets used as [`PointInput`].
157    fn resolve(&'_ self, address: Address) -> FailFuture<'_, ByteNode>;
158    fn resolve_data(&'_ self, address: Address) -> FailFuture<'_, Vec<u8>>;
159    fn try_resolve_local(&self, address: Address) -> Result<Option<ByteNode>> {
160        let _ = address;
161        Ok(None)
162    }
163    /// Get a dynamic extension for a specific [`Address`].
164    fn resolve_extension(&self, address: Address, typeid: TypeId) -> crate::Result<&dyn Any> {
165        let _ = address;
166        let _ = typeid;
167        Err(Error::UnknownExtension)
168    }
169    /// Get a dynamic extension.
170    fn extension(&self, typeid: TypeId) -> crate::Result<&dyn Any> {
171        let _ = typeid;
172        Err(Error::UnknownExtension)
173    }
174}
175
176pub trait FetchBytes: AsAny {
177    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode>;
178    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>>;
179    fn fetch_bytes_local(&self) -> Result<Option<ByteNode>> {
180        Ok(None)
181    }
182    fn fetch_data_local(&self) -> Option<Vec<u8>> {
183        None
184    }
185    fn as_inner(&self) -> Option<&dyn Any> {
186        None
187    }
188}
189
190pub trait Fetch: Send + Sync + FetchBytes {
191    type T;
192    fn fetch_full(&'_ self) -> FailFuture<'_, Node<Self::T>>;
193    fn fetch(&'_ self) -> FailFuture<'_, Self::T>;
194    fn try_fetch_local(&self) -> Result<Option<Node<Self::T>>> {
195        Ok(None)
196    }
197    fn fetch_local(&self) -> Option<Self::T> {
198        None
199    }
200    fn get(&self) -> Option<&Self::T> {
201        None
202    }
203    fn get_mut(&mut self) -> Option<&mut Self::T> {
204        None
205    }
206    fn get_mut_finalize(&mut self) {}
207}
208
209#[derive(ToOutput, InlineOutput, ListHashes, Topological, Parse, ParseInline)]
210pub struct ObjectMarker<T: ?Sized> {
211    object: PhantomData<fn() -> T>,
212}
213
214impl<T: ?Sized> Clone for ObjectMarker<T> {
215    fn clone(&self) -> Self {
216        *self
217    }
218}
219
220impl<T: ?Sized> Copy for ObjectMarker<T> {}
221
222impl<T: ?Sized> Default for ObjectMarker<T> {
223    fn default() -> Self {
224        Self {
225            object: Default::default(),
226        }
227    }
228}
229
230impl<T: ?Sized + Tagged> Tagged for ObjectMarker<T> {}
231
232pub trait PointVisitor {
233    fn visit<T: Traversible>(&mut self, point: &(impl 'static + SingularFetch<T = T> + Clone));
234}
235
236pub struct ReflessInput<'d> {
237    data: Option<&'d [u8]>,
238}
239
240pub struct Input<'d, Extra = ()> {
241    refless: ReflessInput<'d>,
242    resolve: &'d Arc<dyn Resolve>,
243    index: &'d Cell<usize>,
244    extra: &'d Extra,
245}
246
247impl<'a, Extra> Deref for Input<'a, Extra> {
248    type Target = ReflessInput<'a>;
249
250    fn deref(&self) -> &Self::Target {
251        &self.refless
252    }
253}
254
255impl<Extra> DerefMut for Input<'_, Extra> {
256    fn deref_mut(&mut self) -> &mut Self::Target {
257        &mut self.refless
258    }
259}
260
261impl<'a, Extra> Input<'a, Extra> {
262    pub fn replace_extra<E>(self, extra: &'a E) -> Input<'a, E> {
263        Input {
264            refless: self.refless,
265            resolve: self.resolve,
266            index: self.index,
267            extra,
268        }
269    }
270}
271
272impl<'a> ReflessInput<'a> {
273    fn data(&self) -> crate::Result<&'a [u8]> {
274        self.data.ok_or(Error::EndOfInput)
275    }
276
277    fn make_error<T>(&mut self, e: crate::Error) -> crate::Result<T> {
278        self.data = None;
279        Err(e)
280    }
281
282    fn end_of_input<T>(&mut self) -> crate::Result<T> {
283        self.make_error(Error::EndOfInput)
284    }
285}
286
287impl<'d> ParseInput for ReflessInput<'d> {
288    type Data = &'d [u8];
289
290    fn parse_chunk<'a, const N: usize>(&mut self) -> crate::Result<&'a [u8; N]>
291    where
292        Self: 'a,
293    {
294        match self.data()?.split_first_chunk() {
295            Some((chunk, data)) => {
296                self.data = Some(data);
297                Ok(chunk)
298            }
299            None => self.end_of_input(),
300        }
301    }
302
303    fn parse_n(&mut self, n: usize) -> crate::Result<Self::Data> {
304        match self.data()?.split_at_checked(n) {
305            Some((chunk, data)) => {
306                self.data = Some(data);
307                Ok(chunk)
308            }
309            None => self.end_of_input(),
310        }
311    }
312
313    fn parse_until_zero(&mut self) -> crate::Result<Self::Data> {
314        let data = self.data()?;
315        match data.iter().enumerate().find(|(_, x)| **x == 0) {
316            Some((at, _)) => {
317                let (chunk, data) = data.split_at(at);
318                self.data = Some(&data[1..]);
319                Ok(chunk)
320            }
321            None => self.end_of_input(),
322        }
323    }
324
325    fn reparse<T: Parse<Self>>(&mut self, data: Self::Data) -> crate::Result<T> {
326        let input = Self { data: Some(data) };
327        T::parse(input)
328    }
329
330    fn parse_all(self) -> crate::Result<Self::Data> {
331        self.data()
332    }
333
334    fn empty(self) -> crate::Result<()> {
335        if self.data()?.is_empty() {
336            Ok(())
337        } else {
338            Err(Error::ExtraInputLeft)
339        }
340    }
341
342    fn non_empty(self) -> crate::Result<Option<Self>> {
343        Ok(if self.data()?.is_empty() {
344            None
345        } else {
346            Some(self)
347        })
348    }
349}
350
351impl<'d, Extra> ParseInput for Input<'d, Extra> {
352    type Data = &'d [u8];
353
354    fn parse_chunk<'a, const N: usize>(&mut self) -> crate::Result<&'a [u8; N]>
355    where
356        Self: 'a,
357    {
358        (**self).parse_chunk()
359    }
360
361    fn parse_n(&mut self, n: usize) -> crate::Result<Self::Data> {
362        (**self).parse_n(n)
363    }
364
365    fn parse_until_zero(&mut self) -> crate::Result<Self::Data> {
366        (**self).parse_until_zero()
367    }
368
369    fn reparse<T: Parse<Self>>(&mut self, data: Self::Data) -> crate::Result<T> {
370        let input = Self {
371            refless: ReflessInput { data: Some(data) },
372            resolve: self.resolve,
373            index: self.index,
374            extra: self.extra,
375        };
376        T::parse(input)
377    }
378
379    fn parse_all(self) -> crate::Result<Self::Data> {
380        self.refless.parse_all()
381    }
382
383    fn empty(self) -> crate::Result<()> {
384        self.refless.empty()
385    }
386
387    fn non_empty(mut self) -> crate::Result<Option<Self>> {
388        self.refless = match self.refless.non_empty()? {
389            Some(refless) => refless,
390            None => return Ok(None),
391        };
392        Ok(Some(self))
393    }
394}
395
396impl<'d, Extra: 'static + Clone> PointInput for Input<'d, Extra> {
397    type Extra = Extra;
398    type WithExtra<E: 'static + Clone> = Input<'d, E>;
399
400    fn next_index(&mut self) -> usize {
401        let index = self.index.get();
402        self.index.set(index + 1);
403        index
404    }
405
406    fn resolve_arc_ref(&self) -> &Arc<dyn Resolve> {
407        self.resolve
408    }
409
410    fn extra(&self) -> &Self::Extra {
411        self.extra
412    }
413
414    fn map_extra<E: 'static + Clone>(
415        self,
416        f: impl FnOnce(&Self::Extra) -> &E,
417    ) -> Self::WithExtra<E> {
418        let Self {
419            refless,
420            resolve,
421            index,
422            extra,
423        } = self;
424        Input {
425            refless,
426            resolve,
427            index,
428            extra: f(extra),
429        }
430    }
431}
432
433pub trait ToOutput {
434    fn to_output(&self, output: &mut dyn Output);
435
436    fn data_hash(&self) -> Hash {
437        let mut output = HashOutput::default();
438        self.to_output(&mut output);
439        output.hash()
440    }
441
442    fn output<T: Output + Default>(&self) -> T {
443        let mut output = T::default();
444        self.to_output(&mut output);
445        output
446    }
447
448    fn vec(&self) -> Vec<u8> {
449        self.output()
450    }
451}
452
453/// Marker trait indicating that [`ToOutput`] result cannot be extended.
454pub trait InlineOutput: ToOutput {
455    fn slice_to_output(slice: &[Self], output: &mut dyn Output)
456    where
457        Self: Sized,
458    {
459        slice.iter_to_output(output);
460    }
461}
462
463pub trait ListHashes {
464    fn list_hashes(&self, f: &mut impl FnMut(Hash)) {
465        let _ = f;
466    }
467
468    fn topology_hash(&self) -> Hash {
469        let mut hasher = Sha256::new();
470        self.list_hashes(&mut |hash| hasher.update(hash));
471        Hash::from_sha256(hasher.finalize().into())
472    }
473
474    fn point_count(&self) -> usize {
475        let mut count = 0;
476        self.list_hashes(&mut |_| count += 1);
477        count
478    }
479}
480
481pub trait Topological: ListHashes {
482    fn traverse(&self, visitor: &mut impl PointVisitor) {
483        let _ = visitor;
484    }
485
486    fn topology(&self) -> TopoVec {
487        let mut topology = TopoVec::with_capacity(self.point_count());
488        self.traverse(&mut topology);
489        topology
490    }
491}
492
493pub trait Tagged {
494    const TAGS: Tags = Tags(&[], &[]);
495
496    const HASH: Hash =
497        const { Hash::from_sha256(Self::TAGS.const_hash(sha2_const::Sha256::new()).finalize()) };
498}
499
500pub trait ParseSlice: for<'a> Parse<Input<'a>> {
501    fn parse_slice(data: &[u8], resolve: &Arc<dyn Resolve>) -> crate::Result<Self> {
502        Self::parse_slice_extra(data, resolve, &())
503    }
504
505    fn reparse(&self) -> crate::Result<Self>
506    where
507        Self: Traversible,
508    {
509        self.reparse_extra(&())
510    }
511}
512
513impl<T: for<'a> Parse<Input<'a>>> ParseSlice for T {}
514
515pub trait ParseSliceExtra<Extra>: for<'a> Parse<Input<'a, Extra>> {
516    fn parse_slice_extra(
517        data: &[u8],
518        resolve: &Arc<dyn Resolve>,
519        extra: &Extra,
520    ) -> crate::Result<Self> {
521        let input = Input {
522            refless: ReflessInput { data: Some(data) },
523            resolve,
524            index: &Cell::new(0),
525            extra,
526        };
527        let object = Self::parse(input)?;
528        Ok(object)
529    }
530
531    fn reparse_extra(&self, extra: &Extra) -> crate::Result<Self>
532    where
533        Self: Traversible,
534    {
535        Self::parse_slice_extra(&self.vec(), &self.to_resolve(), extra)
536    }
537}
538
539impl<T: for<'a> Parse<Input<'a, Extra>>, Extra> ParseSliceExtra<Extra> for T {}
540
541#[derive(ToOutput)]
542pub struct ObjectHashes {
543    pub tags: Hash,
544    pub topology: Hash,
545    pub data: Hash,
546}
547
548pub trait FullHash: ToOutput + ListHashes + Tagged {
549    fn hashes(&self) -> ObjectHashes {
550        ObjectHashes {
551            tags: Self::HASH,
552            topology: self.topology_hash(),
553            data: self.data_hash(),
554        }
555    }
556
557    fn full_hash(&self) -> Hash {
558        self.hashes().data_hash()
559    }
560}
561
562impl<T: ?Sized + ToOutput + ListHashes + Tagged> FullHash for T {}
563
564pub trait Traversible: 'static + Sized + Send + Sync + FullHash + Topological {
565    fn to_resolve(&self) -> Arc<dyn Resolve> {
566        Arc::new(ByTopology {
567            topology: self.topology(),
568        })
569    }
570}
571
572impl<T: 'static + Send + Sync + FullHash + Topological> Traversible for T {}
573
574pub trait Object<Extra = ()>: Traversible + for<'a> Parse<Input<'a, Extra>> {}
575
576impl<T: Traversible + for<'a> Parse<Input<'a, Extra>>, Extra> Object<Extra> for T {}
577
578pub struct Tags(pub &'static [&'static str], pub &'static [&'static Self]);
579
580impl Tags {
581    const fn const_hash(&self, mut hasher: sha2_const::Sha256) -> sha2_const::Sha256 {
582        {
583            let mut i = 0;
584            while i < self.0.len() {
585                hasher = hasher.update(self.0[i].as_bytes());
586                i += 1;
587            }
588        }
589        {
590            let mut i = 0;
591            while i < self.1.len() {
592                hasher = self.1[i].const_hash(hasher);
593                i += 1;
594            }
595        }
596        hasher
597    }
598}
599
600pub trait Inline<Extra = ()>:
601    Object<Extra> + InlineOutput + for<'a> ParseInline<Input<'a, Extra>>
602{
603}
604
605impl<T: Object<Extra> + InlineOutput + for<'a> ParseInline<Input<'a, Extra>>, Extra> Inline<Extra>
606    for T
607{
608}
609
610pub trait Topology: Send + Sync {
611    fn len(&self) -> usize;
612    fn get(&self, index: usize) -> Option<&Arc<dyn Singular>>;
613
614    fn is_empty(&self) -> bool {
615        self.len() == 0
616    }
617}
618
619pub trait Singular: Send + Sync + FetchBytes {
620    fn hash(&self) -> Hash;
621}
622
623pub trait SingularFetch: Singular + Fetch {}
624
625impl<T: ?Sized + Singular + Fetch> SingularFetch for T {}
626
627pub type TopoVec = Vec<Arc<dyn Singular>>;
628
629impl PointVisitor for TopoVec {
630    fn visit<T: Traversible>(&mut self, point: &(impl 'static + SingularFetch<T = T> + Clone)) {
631        self.push(Arc::new(point.clone()));
632    }
633}
634
635impl Topology for TopoVec {
636    fn len(&self) -> usize {
637        self.len()
638    }
639
640    fn get(&self, index: usize) -> Option<&Arc<dyn Singular>> {
641        (**self).get(index)
642    }
643}
644
645pub trait ParseSliceRefless: for<'a> Parse<ReflessInput<'a>> {
646    fn parse_slice_refless(data: &[u8]) -> crate::Result<Self> {
647        let input = ReflessInput { data: Some(data) };
648        let object = Self::parse(input)?;
649        Ok(object)
650    }
651}
652
653impl<T: for<'a> Parse<ReflessInput<'a>>> ParseSliceRefless for T {}
654
655pub trait ReflessObject:
656    'static + Sized + Send + Sync + ToOutput + Tagged + for<'a> Parse<ReflessInput<'a>>
657{
658}
659
660impl<T: 'static + Sized + Send + Sync + ToOutput + Tagged + for<'a> Parse<ReflessInput<'a>>>
661    ReflessObject for T
662{
663}
664
665pub trait ReflessInline:
666    ReflessObject + InlineOutput + for<'a> ParseInline<ReflessInput<'a>>
667{
668}
669
670impl<T: ReflessObject + InlineOutput + for<'a> ParseInline<ReflessInput<'a>>> ReflessInline for T {}
671
672pub trait Output {
673    fn write(&mut self, data: &[u8]);
674}
675
676impl Output for Vec<u8> {
677    fn write(&mut self, data: &[u8]) {
678        self.extend_from_slice(data);
679    }
680}
681
682#[derive(Default)]
683struct HashOutput {
684    hasher: Sha256,
685    at: usize,
686}
687
688impl Output for HashOutput {
689    fn write(&mut self, data: &[u8]) {
690        self.hasher.update(data);
691        self.at += data.len();
692    }
693}
694
695impl HashOutput {
696    fn hash(self) -> Hash {
697        Hash::from_sha256(self.hasher.finalize().into())
698    }
699}
700
701struct ByTopology {
702    topology: TopoVec,
703}
704
705impl ByTopology {
706    fn try_resolve(&'_ self, address: Address) -> Result<FailFuture<'_, ByteNode>> {
707        let point = self
708            .topology
709            .get(address.index)
710            .ok_or(Error::AddressOutOfBounds)?;
711        if point.hash() != address.hash {
712            Err(Error::ResolutionMismatch)
713        } else {
714            Ok(point.fetch_bytes())
715        }
716    }
717
718    fn try_resolve_data(&'_ self, address: Address) -> Result<FailFuture<'_, Vec<u8>>> {
719        let point = self
720            .topology
721            .get(address.index)
722            .ok_or(Error::AddressOutOfBounds)?;
723        if point.hash() != address.hash {
724            Err(Error::ResolutionMismatch)
725        } else {
726            Ok(point.fetch_data())
727        }
728    }
729}
730
731impl Resolve for ByTopology {
732    fn resolve(&'_ self, address: Address) -> FailFuture<'_, ByteNode> {
733        self.try_resolve(address)
734            .map_err(Err)
735            .map_err(ready)
736            .map_err(Box::pin)
737            .unwrap_or_else(|x| x)
738    }
739
740    fn resolve_data(&'_ self, address: Address) -> FailFuture<'_, Vec<u8>> {
741        self.try_resolve_data(address)
742            .map_err(Err)
743            .map_err(ready)
744            .map_err(Box::pin)
745            .unwrap_or_else(|x| x)
746    }
747
748    fn try_resolve_local(&self, address: Address) -> Result<Option<ByteNode>> {
749        let point = self
750            .topology
751            .get(address.index)
752            .ok_or(Error::AddressOutOfBounds)?;
753        if point.hash() != address.hash {
754            Err(Error::ResolutionMismatch)
755        } else {
756            point.fetch_bytes_local()
757        }
758    }
759}
760
761pub trait Size {
762    const SIZE: usize = <Self::Size as Unsigned>::USIZE;
763    type Size: Unsigned;
764}
765
766pub trait SizeExt: Size<Size: ArrayLength> + ToOutput {
767    fn to_array(&self) -> GenericArray<u8, Self::Size> {
768        let mut array = GenericArray::default();
769        let mut output = ArrayOutput {
770            data: &mut array,
771            offset: 0,
772        };
773        self.to_output(&mut output);
774        output.finalize();
775        array
776    }
777}
778
779impl<T: Size<Size: ArrayLength> + ToOutput> SizeExt for T {}
780
781struct ArrayOutput<'a> {
782    data: &'a mut [u8],
783    offset: usize,
784}
785
786impl ArrayOutput<'_> {
787    fn finalize(self) {
788        assert_eq!(self.offset, self.data.len());
789    }
790}
791
792impl Output for ArrayOutput<'_> {
793    fn write(&mut self, data: &[u8]) {
794        self.data[self.offset..][..data.len()].copy_from_slice(data);
795        self.offset += data.len();
796    }
797}
798
799trait RainbowIterator: Sized + IntoIterator {
800    fn iter_to_output(self, output: &mut dyn Output)
801    where
802        Self::Item: InlineOutput,
803    {
804        self.into_iter().for_each(|item| item.to_output(output));
805    }
806
807    fn iter_list_hashes(self, f: &mut impl FnMut(Hash))
808    where
809        Self::Item: ListHashes,
810    {
811        self.into_iter().for_each(|item| item.list_hashes(f));
812    }
813
814    fn iter_traverse(self, visitor: &mut impl PointVisitor)
815    where
816        Self::Item: Topological,
817    {
818        self.into_iter().for_each(|item| item.traverse(visitor));
819    }
820}
821
822pub trait ParseInput: Sized {
823    type Data: AsRef<[u8]> + Deref<Target = [u8]> + Into<Vec<u8>> + Copy;
824    fn parse_chunk<'a, const N: usize>(&mut self) -> crate::Result<&'a [u8; N]>
825    where
826        Self: 'a;
827    fn parse_n(&mut self, n: usize) -> crate::Result<Self::Data>;
828    fn parse_until_zero(&mut self) -> crate::Result<Self::Data>;
829    fn parse_n_compare(&mut self, n: usize, c: &[u8]) -> crate::Result<Option<Self::Data>> {
830        let data = self.parse_n(n)?;
831        if *data == *c {
832            Ok(None)
833        } else {
834            Ok(Some(data))
835        }
836    }
837    fn reparse<T: Parse<Self>>(&mut self, data: Self::Data) -> crate::Result<T>;
838    fn parse_ahead<T: Parse<Self>>(&mut self, n: usize) -> crate::Result<T> {
839        let data = self.parse_n(n)?;
840        self.reparse(data)
841    }
842    fn parse_zero_terminated<T: Parse<Self>>(&mut self) -> crate::Result<T> {
843        let data = self.parse_until_zero()?;
844        self.reparse(data)
845    }
846    fn parse_compare<T: Parse<Self>>(&mut self, n: usize, c: &[u8]) -> Result<Option<T>> {
847        self.parse_n_compare(n, c)?
848            .map(|data| self.reparse(data))
849            .transpose()
850    }
851    fn parse_all(self) -> crate::Result<Self::Data>;
852    fn empty(self) -> crate::Result<()>;
853    fn non_empty(self) -> crate::Result<Option<Self>>;
854
855    fn consume(self, f: impl FnMut(&mut Self) -> crate::Result<()>) -> crate::Result<()> {
856        self.collect(f)
857    }
858
859    fn parse_collect<T: ParseInline<Self>, B: FromIterator<T>>(self) -> crate::Result<B> {
860        self.collect(|input| input.parse_inline())
861    }
862
863    fn collect<T, B: FromIterator<T>>(
864        self,
865        f: impl FnMut(&mut Self) -> crate::Result<T>,
866    ) -> crate::Result<B> {
867        self.iter(f).collect()
868    }
869
870    fn iter<T>(
871        self,
872        mut f: impl FnMut(&mut Self) -> crate::Result<T>,
873    ) -> impl Iterator<Item = crate::Result<T>> {
874        let mut state = Some(self);
875        std::iter::from_fn(move || {
876            let mut input = match state.take()?.non_empty() {
877                Ok(input) => input?,
878                Err(e) => return Some(Err(e)),
879            };
880            let item = f(&mut input);
881            state = Some(input);
882            Some(item)
883        })
884    }
885
886    fn parse_inline<T: ParseInline<Self>>(&mut self) -> crate::Result<T> {
887        T::parse_inline(self)
888    }
889
890    fn parse<T: Parse<Self>>(self) -> crate::Result<T> {
891        T::parse(self)
892    }
893
894    fn parse_vec<T: ParseInline<Self>>(self) -> crate::Result<Vec<T>> {
895        T::parse_vec(self)
896    }
897}
898
899pub trait PointInput: ParseInput {
900    type Extra: 'static + Clone;
901    type WithExtra<E: 'static + Clone>: PointInput<Extra = E, WithExtra<Self::Extra> = Self>;
902    fn next_index(&mut self) -> usize;
903    fn resolve_arc_ref(&self) -> &Arc<dyn Resolve>;
904    fn resolve(&self) -> Arc<dyn Resolve> {
905        self.resolve_arc_ref().clone()
906    }
907    fn resolve_ref(&self) -> &dyn Resolve {
908        self.resolve_arc_ref().as_ref()
909    }
910    fn extension<T: Any>(&self) -> crate::Result<&T> {
911        self.resolve_ref()
912            .extension(TypeId::of::<T>())?
913            .downcast_ref()
914            .ok_or(Error::ExtensionType)
915    }
916    fn extra(&self) -> &Self::Extra;
917    fn map_extra<E: 'static + Clone>(
918        self,
919        f: impl FnOnce(&Self::Extra) -> &E,
920    ) -> Self::WithExtra<E>;
921}
922
923impl<T: Sized + IntoIterator> RainbowIterator for T {}
924
925pub trait Parse<I: ParseInput>: Sized {
926    fn parse(input: I) -> crate::Result<Self>;
927}
928
929pub trait ParseInline<I: ParseInput>: Parse<I> {
930    fn parse_inline(input: &mut I) -> crate::Result<Self>;
931    fn parse_as_inline(mut input: I) -> crate::Result<Self> {
932        let object = Self::parse_inline(&mut input)?;
933        input.empty()?;
934        Ok(object)
935    }
936    fn parse_vec(input: I) -> crate::Result<Vec<Self>> {
937        input.parse_collect()
938    }
939}
940
941/// Implemented if both types have the exact same layout.
942/// This implies having the same [`MaybeHasNiche::MnArray`].
943///
944/// This is represented as two-way conversion for two reasons:
945/// - to highlight that the conversion is actual equivalence
946/// - to increase flexibility (mostly to go around the orphan rule)
947pub trait Equivalent<T>: Sized {
948    /// Inverse of [`Equivalent::from_equivalent`].
949    fn into_equivalent(self) -> T;
950    /// Inverse of [`Equivalent::into_equivalent`].
951    fn from_equivalent(object: T) -> Self;
952}
953
954pub trait ExtraFor<T> {
955    fn parse(&self, data: &[u8], resolve: &Arc<dyn Resolve>) -> Result<T>;
956}
957
958impl<T: for<'a> Parse<Input<'a, Extra>>, Extra> ExtraFor<T> for Extra {
959    fn parse(&self, data: &[u8], resolve: &Arc<dyn Resolve>) -> Result<T> {
960        T::parse_slice_extra(data, resolve, self)
961    }
962}
963
964#[test]
965fn options() {
966    type T0 = ();
967    type T1 = Option<T0>;
968    type T2 = Option<T1>;
969    type T3 = Option<T2>;
970    type T4 = Option<T3>;
971    type T5 = Option<T4>;
972    assert_eq!(T0::SIZE, 0);
973    assert_eq!(T1::SIZE, 1);
974    assert_eq!(T2::SIZE, 1);
975    assert_eq!(T3::SIZE, 1);
976    assert_eq!(T4::SIZE, 1);
977    assert_eq!(T5::SIZE, 1);
978    assert_eq!(Some(Some(Some(()))).vec(), [0]);
979    assert_eq!(Some(Some(None::<()>)).vec(), [1]);
980    assert_eq!(Some(None::<Option<()>>).vec(), [2]);
981    assert_eq!(None::<Option<Option<()>>>.vec(), [3]);
982
983    assert_eq!(false.vec(), [0]);
984    assert_eq!(true.vec(), [1]);
985    assert_eq!(Some(false).vec(), [0]);
986    assert_eq!(Some(true).vec(), [1]);
987    assert_eq!(None::<bool>.vec(), [2]);
988    assert_eq!(Some(Some(false)).vec(), [0]);
989    assert_eq!(Some(Some(true)).vec(), [1]);
990    assert_eq!(Some(None::<bool>).vec(), [2]);
991    assert_eq!(None::<Option<bool>>.vec(), [3]);
992    assert_eq!(Some(Some(Some(false))).vec(), [0]);
993    assert_eq!(Some(Some(Some(true))).vec(), [1]);
994    assert_eq!(Some(Some(None::<bool>)).vec(), [2]);
995    assert_eq!(Some(None::<Option<bool>>).vec(), [3]);
996    assert_eq!(None::<Option<Option<bool>>>.vec(), [4]);
997    assert_eq!(Option::<Hash>::SIZE, HASH_SIZE);
998    assert_eq!(Some(()).vec(), [0]);
999    assert_eq!(Some(((), ())).vec(), [0]);
1000    assert_eq!(Some(((), true)).vec(), [1]);
1001    assert_eq!(Some((true, true)).vec(), [1, 1]);
1002    assert_eq!(Some((Some(true), true)).vec(), [1, 1]);
1003    assert_eq!(Some((None::<bool>, true)).vec(), [2, 1]);
1004    assert_eq!(Some((true, None::<bool>)).vec(), [1, 2]);
1005    assert_eq!(None::<(Option<bool>, bool)>.vec(), [3, 2]);
1006    assert_eq!(None::<(bool, Option<bool>)>.vec(), [2, 3]);
1007    assert_eq!(Some(Some((Some(true), Some(true)))).vec(), [1, 1],);
1008    assert_eq!(Option::<Hash>::SIZE, HASH_SIZE);
1009    assert_eq!(Option::<Option<Hash>>::SIZE, HASH_SIZE);
1010    assert_eq!(Option::<Option<Option<Hash>>>::SIZE, HASH_SIZE);
1011}