object_rainbow/
lib.rs

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