object_rainbow/
lib.rs

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