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