object_rainbow/
lib.rs

1extern crate self as object_rainbow;
2
3use std::{
4    any::{Any, TypeId},
5    cell::Cell,
6    convert::Infallible,
7    future::ready,
8    marker::PhantomData,
9    ops::{Deref, DerefMut},
10    pin::Pin,
11    sync::Arc,
12};
13
14pub use anyhow::anyhow;
15use futures_util::TryFutureExt;
16use generic_array::{ArrayLength, GenericArray};
17pub use object_rainbow_derive::{
18    Enum, Inline, MaybeHasNiche, Object, Parse, ParseAsInline, ParseInline, ReflessInline,
19    ReflessObject, Size, Tagged, ToOutput, Topological,
20};
21use sha2::{Digest, Sha256};
22#[doc(hidden)]
23pub use typenum;
24use typenum::Unsigned;
25
26pub use self::enumkind::Enum;
27pub use self::hash::{Hash, OptionalHash};
28pub use self::niche::{
29    AutoEnumNiche, AutoNiche, HackNiche, MaybeHasNiche, Niche, NicheForUnsized, NoNiche, OneNiche,
30    SomeNiche, ZeroNiche, ZeroNoNiche,
31};
32#[doc(hidden)]
33pub use self::niche::{MaybeNiche, MnArray, NicheFoldOrArray, NicheOr};
34
35pub mod enumkind;
36mod hash;
37pub mod hashed;
38mod impls;
39pub mod length_prefixed;
40mod niche;
41pub mod numeric;
42mod sha2_const;
43
44#[macro_export]
45/// Construct [`Error::Parse`].
46macro_rules! error_parse {
47    ($($t:tt)*) => {
48        $crate::Error::Parse($crate::anyhow!($($t)*))
49    };
50}
51
52#[macro_export]
53/// Construct [`Error::Fetch`].
54macro_rules! error_fetch {
55    ($($t:tt)*) => {
56        $crate::Error::Fetch($crate::anyhow!($($t)*))
57    };
58}
59
60/// Errors encountered during fetching an object. Mostly related to parsing.
61#[derive(Debug, thiserror::Error)]
62#[non_exhaustive]
63pub enum Error {
64    /// Arbitrary parsing error.
65    #[error(transparent)]
66    Parse(anyhow::Error),
67    /// Arbitrary fetching error.
68    #[error(transparent)]
69    Fetch(anyhow::Error),
70    /// Data left after an [`Inline`] got parsed.
71    #[error("extra input left")]
72    ExtraInputLeft,
73    /// EOF.
74    #[error("end of input")]
75    EndOfInput,
76    /// Overran [`PointInput`]'s [`Address`] vector.
77    #[error("address index out of bounds")]
78    AddressOutOfBounds,
79    /// [`Address::hash`] doesn't match what [`Resolve`] returned.
80    #[error("hash resolution mismatch")]
81    ResolutionMismatch,
82    /// [`FullHash::full_hash`] doesn't match [`Singular::hash`].
83    #[error("data hash mismatch")]
84    DataMismatch,
85    /// Discriminant out of range for an [`Enum`].
86    #[error("discriminant overflow")]
87    DiscriminantOverflow,
88    /// Unepxected zero for a non-zero value.
89    #[error("zero")]
90    Zero,
91    /// Value out of bounds for a certain type.
92    #[error("out of bounds")]
93    OutOfBounds,
94    /// Current architecture (32-bit) is unable to handle lengths of this size.
95    #[error("length out of bounds")]
96    UnsupportedLength,
97    /// Not UTF-8.
98    #[error(transparent)]
99    Utf8(std::string::FromUtf8Error),
100    /// [`Resolve::extension`] (or related things) were unable to resolve the extension.
101    #[error("unknown extension")]
102    UnknownExtension,
103    /// Extension type didn't match what we asked for. This might be turned into panic later.
104    #[error("wrong extension type")]
105    ExtensionType,
106}
107
108impl Error {
109    /// Construct [`Error::Parse`] from another error.
110    pub fn parse(e: impl Into<anyhow::Error>) -> Self {
111        Self::Parse(e.into())
112    }
113
114    /// Construct [`Error::Fetch`] from another error.
115    pub fn fetch(e: impl Into<anyhow::Error>) -> Self {
116        Self::Fetch(e.into())
117    }
118}
119
120pub type Result<T> = std::result::Result<T, Error>;
121
122/// SHA-256 hash size in bytes.
123pub const HASH_SIZE: usize = sha2_const::Sha256::DIGEST_SIZE;
124
125/// Address within a [`PointInput`].
126///
127/// This was introduced:
128/// - to avoid using a [`Hash`]-only map
129/// - to differentiate between separate [`Point`]s within a context
130#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ParseAsInline)]
131pub struct Address {
132    /// Monotonically incremented index. This is not present at all in the actual format.
133    pub index: usize,
134    /// Only this part is part of the parsed/generated input.
135    pub hash: Hash,
136}
137
138impl Address {
139    /// Construct an address which is invalid within parsing context, but can be used in map-based
140    /// [`Resolve`]s.
141    pub fn from_hash(hash: Hash) -> Self {
142        Self {
143            index: usize::MAX,
144            hash,
145        }
146    }
147}
148
149impl<I: PointInput> ParseInline<I> for Address {
150    fn parse_inline(input: &mut I) -> crate::Result<Self> {
151        Ok(Self {
152            index: input.next_index(),
153            hash: input.parse_inline()?,
154        })
155    }
156}
157
158/// Fallible future type yielding either `T` or [`Error`].
159pub type FailFuture<'a, T> = Pin<Box<dyn 'a + Send + Future<Output = Result<T>>>>;
160
161/// Returned by [`Resolve`] and [`FetchBytes`]. Represents traversal through the object graph.
162pub type ByteNode = (Vec<u8>, Arc<dyn Resolve>);
163
164trait FromInner {
165    type Inner: 'static + Clone;
166    type Extra: 'static + Clone;
167
168    fn from_inner(inner: Self::Inner, extra: Self::Extra) -> Self;
169}
170
171/// Trait for contextually using [`Any`]. Can itself be implemented for non-`'static` and `?Sized`
172/// types, and is `dyn`-compatible.
173pub trait AsAny {
174    /// Get a shared RTTI reference.
175    fn any_ref(&self) -> &dyn Any
176    where
177        Self: 'static;
178    /// Get an exclusive RTTI reference.
179    fn any_mut(&mut self) -> &mut dyn Any
180    where
181        Self: 'static;
182    /// Get an RTTI [`Box`].
183    fn any_box(self: Box<Self>) -> Box<dyn Any>
184    where
185        Self: 'static;
186    /// Get an RTTI [`Arc`].
187    fn any_arc(self: Arc<Self>) -> Arc<dyn Any>
188    where
189        Self: 'static;
190    /// Get an RTTI [`Arc`] which is also [`Send`].
191    fn any_arc_sync(self: Arc<Self>) -> Arc<dyn Send + Sync + Any>
192    where
193        Self: 'static + Send + Sync;
194}
195
196impl<T> AsAny for T {
197    fn any_ref(&self) -> &dyn Any
198    where
199        Self: 'static,
200    {
201        self
202    }
203
204    fn any_mut(&mut self) -> &mut dyn Any
205    where
206        Self: 'static,
207    {
208        self
209    }
210
211    fn any_box(self: Box<Self>) -> Box<dyn Any>
212    where
213        Self: 'static,
214    {
215        self
216    }
217
218    fn any_arc(self: Arc<Self>) -> Arc<dyn Any>
219    where
220        Self: 'static,
221    {
222        self
223    }
224
225    fn any_arc_sync(self: Arc<Self>) -> Arc<dyn Send + Sync + Any>
226    where
227        Self: 'static + Send + Sync,
228    {
229        self
230    }
231}
232
233/// Something that resolve [`Address`]es to [`ByteNode`]s.
234pub trait Resolve: Send + Sync + AsAny {
235    /// Resolve the address. For an [`Object`], this is what gets used as [`PointInput`].
236    fn resolve(&'_ self, address: Address) -> FailFuture<'_, ByteNode>;
237    fn resolve_data(&'_ self, address: Address) -> FailFuture<'_, Vec<u8>>;
238    /// Get a dynamic extension for a specific [`Address`].
239    fn resolve_extension(&self, address: Address, typeid: TypeId) -> crate::Result<&dyn Any> {
240        let _ = address;
241        let _ = typeid;
242        Err(Error::UnknownExtension)
243    }
244    /// Get a dynamic extension.
245    fn extension(&self, typeid: TypeId) -> crate::Result<&dyn Any> {
246        let _ = typeid;
247        Err(Error::UnknownExtension)
248    }
249    /// Self-identification of the resolver type.
250    fn name(&self) -> &str;
251}
252
253pub trait FetchBytes: AsAny {
254    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode>;
255    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>>;
256    fn as_inner(&self) -> Option<&dyn Any> {
257        None
258    }
259}
260
261pub trait Fetch: Send + Sync + FetchBytes {
262    type T;
263    fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)>;
264    fn fetch(&'_ self) -> FailFuture<'_, Self::T>;
265    fn get(&self) -> Option<&Self::T> {
266        None
267    }
268    fn get_mut(&mut self) -> Option<&mut Self::T> {
269        None
270    }
271    fn get_mut_finalize(&mut self) {}
272}
273
274trait FetchBytesExt: FetchBytes {
275    fn inner_cast<T: FromInner>(&self, extra: &T::Extra) -> Option<T> {
276        self.as_inner()?
277            .downcast_ref()
278            .cloned()
279            .map(|inner| T::from_inner(inner, extra.clone()))
280    }
281}
282
283impl<T: ?Sized + FetchBytes> FetchBytesExt for T {}
284
285#[derive(Clone, ParseAsInline)]
286pub struct RawPointInner {
287    hash: Hash,
288    origin: Arc<dyn Send + Sync + FetchBytes>,
289}
290
291impl RawPointInner {
292    pub fn cast<T, Extra: 'static + Clone>(self, extra: Extra) -> RawPoint<T, Extra> {
293        RawPoint::from_inner(self, extra)
294    }
295}
296
297impl RawPointInner {
298    pub fn from_address(address: Address, resolve: Arc<dyn Resolve>) -> Self {
299        Self {
300            hash: address.hash,
301            origin: Arc::new(ByAddressInner { address, resolve }),
302        }
303    }
304}
305
306impl ToOutput for RawPointInner {
307    fn to_output(&self, output: &mut dyn Output) {
308        self.hash.to_output(output);
309    }
310}
311
312impl<I: PointInput> ParseInline<I> for RawPointInner {
313    fn parse_inline(input: &mut I) -> crate::Result<Self> {
314        Ok(Self::from_address(input.parse_inline()?, input.resolve()))
315    }
316}
317
318impl Tagged for RawPointInner {}
319
320impl Singular for RawPointInner {
321    fn hash(&self) -> Hash {
322        self.hash
323    }
324}
325
326impl<T, Extra: 'static + Send + Sync> Singular for RawPoint<T, Extra> {
327    fn hash(&self) -> Hash {
328        self.inner.hash()
329    }
330}
331
332#[derive(ToOutput, Topological, Parse, ParseInline)]
333pub struct ObjectMarker<T: ?Sized> {
334    object: PhantomData<fn() -> T>,
335}
336
337impl<T: ?Sized> Clone for ObjectMarker<T> {
338    fn clone(&self) -> Self {
339        *self
340    }
341}
342
343impl<T: ?Sized> Copy for ObjectMarker<T> {}
344
345impl<T: ?Sized> Default for ObjectMarker<T> {
346    fn default() -> Self {
347        Self {
348            object: Default::default(),
349        }
350    }
351}
352
353impl<T: ?Sized + Tagged> Tagged for ObjectMarker<T> {}
354impl<T: ?Sized + 'static + Tagged, Extra: 'static> Object<Extra> for ObjectMarker<T> {}
355impl<T: ?Sized + 'static + Tagged, Extra: 'static> Inline<Extra> for ObjectMarker<T> {}
356
357#[derive(Clone, ParseAsInline)]
358struct Extras<Extra>(Extra);
359
360impl<Extra> Deref for Extras<Extra> {
361    type Target = Extra;
362
363    fn deref(&self) -> &Self::Target {
364        &self.0
365    }
366}
367
368impl<Extra> ToOutput for Extras<Extra> {
369    fn to_output(&self, _: &mut dyn Output) {}
370}
371
372impl<I: PointInput> ParseInline<I> for Extras<I::Extra> {
373    fn parse_inline(input: &mut I) -> crate::Result<Self> {
374        Ok(Self(input.extra().clone()))
375    }
376}
377
378impl<Extra> Tagged for Extras<Extra> {}
379impl<Extra> Topological for Extras<Extra> {}
380impl<Extra: 'static + Send + Sync + Clone> Object<Extra> for Extras<Extra> {}
381impl<Extra: 'static + Send + Sync + Clone> Inline<Extra> for Extras<Extra> {}
382
383#[derive(ToOutput, Tagged, Parse, ParseInline)]
384pub struct RawPoint<T = Infallible, Extra = ()> {
385    inner: RawPointInner,
386    extra: Extras<Extra>,
387    object: ObjectMarker<T>,
388}
389
390impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Topological for RawPoint<T, Extra> {
391    fn accept_points(&self, visitor: &mut impl PointVisitor) {
392        visitor.visit(&self.clone().point());
393    }
394
395    fn point_count(&self) -> usize {
396        1
397    }
398}
399
400impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Object<Extra> for RawPoint<T, Extra> {}
401impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Inline<Extra> for RawPoint<T, Extra> {}
402
403impl<T, Extra: 'static + Clone> FromInner for RawPoint<T, Extra> {
404    type Inner = RawPointInner;
405    type Extra = Extra;
406
407    fn from_inner(inner: Self::Inner, extra: Self::Extra) -> Self {
408        RawPoint {
409            inner,
410            extra: Extras(extra),
411            object: Default::default(),
412        }
413    }
414}
415
416impl<T, Extra: Clone> Clone for RawPoint<T, Extra> {
417    fn clone(&self) -> Self {
418        Self {
419            inner: self.inner.clone(),
420            extra: self.extra.clone(),
421            object: Default::default(),
422        }
423    }
424}
425
426impl<T> Point<T> {
427    pub fn raw<Extra: 'static + Clone>(self, extra: Extra) -> RawPoint<T, Extra> {
428        {
429            if let Some(raw) = self.origin.inner_cast(&extra) {
430                return raw;
431            }
432        }
433        RawPointInner {
434            hash: self.hash.unwrap(),
435            origin: self.origin,
436        }
437        .cast(extra)
438    }
439}
440
441impl<T, Extra: 'static + Clone> RawPoint<T, Extra> {
442    pub fn cast<U>(self) -> RawPoint<U, Extra> {
443        self.inner.cast(self.extra.0)
444    }
445}
446
447impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> RawPoint<T, Extra> {
448    pub fn point(self) -> Point<T> {
449        Point::from_origin(self.inner.hash, Arc::new(self))
450    }
451}
452
453impl FetchBytes for RawPointInner {
454    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
455        self.origin.fetch_bytes()
456    }
457
458    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
459        self.origin.fetch_data()
460    }
461}
462
463impl<T, Extra: 'static> FetchBytes for RawPoint<T, Extra> {
464    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
465        self.inner.fetch_bytes()
466    }
467
468    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
469        self.inner.fetch_data()
470    }
471
472    fn as_inner(&self) -> Option<&dyn Any> {
473        Some(&self.inner)
474    }
475}
476
477impl<T: Object<Extra>, Extra: 'static + Send + Sync> Fetch for RawPoint<T, Extra> {
478    type T = T;
479
480    fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
481        Box::pin(async {
482            let (data, resolve) = self.inner.origin.fetch_bytes().await?;
483            let object = T::parse_slice_extra(&data, &resolve, &self.extra)?;
484            if self.inner.hash != object.full_hash() {
485                Err(Error::DataMismatch)
486            } else {
487                Ok((object, resolve))
488            }
489        })
490    }
491
492    fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
493        Box::pin(async {
494            let (data, resolve) = self.inner.origin.fetch_bytes().await?;
495            let object = T::parse_slice_extra(&data, &resolve, &self.extra)?;
496            if self.inner.hash != object.full_hash() {
497                Err(Error::DataMismatch)
498            } else {
499                Ok(object)
500            }
501        })
502    }
503}
504
505impl<T> Point<T> {
506    pub fn extract_resolve<R: Any>(&self) -> Option<(&Address, &R)> {
507        let ByAddressInner { address, resolve } =
508            self.origin.as_inner()?.downcast_ref::<ByAddressInner>()?;
509        let resolve = resolve.as_ref().any_ref().downcast_ref::<R>()?;
510        Some((address, resolve))
511    }
512}
513
514#[derive(ParseAsInline)]
515#[must_use]
516pub struct Point<T> {
517    hash: OptionalHash,
518    origin: Arc<dyn Fetch<T = T>>,
519}
520
521impl<T> PartialOrd for Point<T> {
522    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
523        Some(self.cmp(other))
524    }
525}
526
527impl<T> Ord for Point<T> {
528    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
529        self.hash().cmp(&other.hash())
530    }
531}
532
533impl<T> Eq for Point<T> {}
534
535impl<T> PartialEq for Point<T> {
536    fn eq(&self, other: &Self) -> bool {
537        self.hash() == other.hash()
538    }
539}
540
541impl<T> Clone for Point<T> {
542    fn clone(&self) -> Self {
543        Self {
544            hash: self.hash,
545            origin: self.origin.clone(),
546        }
547    }
548}
549
550impl<T> Point<T> {
551    pub fn from_origin(hash: Hash, origin: Arc<dyn Fetch<T = T>>) -> Self {
552        Self {
553            hash: hash.into(),
554            origin,
555        }
556    }
557
558    fn map_origin<U>(
559        self,
560        f: impl FnOnce(Arc<dyn Fetch<T = T>>) -> Arc<dyn Fetch<T = U>>,
561    ) -> Point<U> {
562        Point {
563            hash: self.hash,
564            origin: f(self.origin),
565        }
566    }
567}
568
569impl<T> Size for Point<T> {
570    const SIZE: usize = HASH_SIZE;
571    type Size = typenum::generic_const_mappings::U<HASH_SIZE>;
572}
573
574impl<T: Object> Point<T> {
575    pub fn from_address(address: Address, resolve: Arc<dyn Resolve>) -> Self {
576        Self::from_address_extra(address, resolve, ())
577    }
578}
579
580impl<T> Point<T> {
581    pub fn from_address_extra<Extra: 'static + Send + Sync + Clone>(
582        address: Address,
583        resolve: Arc<dyn Resolve>,
584        extra: Extra,
585    ) -> Self
586    where
587        T: Object<Extra>,
588    {
589        Self::from_origin(
590            address.hash,
591            Arc::new(ByAddress::from_inner(
592                ByAddressInner { address, resolve },
593                extra,
594            )),
595        )
596    }
597
598    pub fn with_resolve<Extra: 'static + Send + Sync + Clone>(
599        &self,
600        resolve: Arc<dyn Resolve>,
601        extra: Extra,
602    ) -> Self
603    where
604        T: Object<Extra>,
605    {
606        Self::from_address_extra(Address::from_hash(self.hash()), resolve, extra)
607    }
608}
609
610#[derive(Clone)]
611struct ByAddressInner {
612    address: Address,
613    resolve: Arc<dyn Resolve>,
614}
615
616impl FetchBytes for ByAddressInner {
617    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
618        self.resolve.resolve(self.address)
619    }
620
621    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
622        self.resolve.resolve_data(self.address)
623    }
624}
625
626struct ByAddress<T, Extra> {
627    inner: ByAddressInner,
628    extra: Extra,
629    _object: PhantomData<fn() -> T>,
630}
631
632impl<T, Extra: 'static + Clone> ByAddress<T, Extra> {
633    fn from_inner(inner: ByAddressInner, extra: Extra) -> Self {
634        Self {
635            inner,
636            extra,
637            _object: PhantomData,
638        }
639    }
640}
641
642impl<T, Extra: 'static> FetchBytes for ByAddress<T, Extra> {
643    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
644        self.inner.fetch_bytes()
645    }
646
647    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
648        self.inner.fetch_data()
649    }
650
651    fn as_inner(&self) -> Option<&dyn Any> {
652        Some(&self.inner)
653    }
654}
655
656impl<T: Object<Extra>, Extra: 'static + Send + Sync> Fetch for ByAddress<T, Extra> {
657    type T = T;
658
659    fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
660        Box::pin(async {
661            let (data, resolve) = self.fetch_bytes().await?;
662            let object = T::parse_slice_extra(&data, &resolve, &self.extra)?;
663            if self.inner.address.hash != object.full_hash() {
664                Err(Error::DataMismatch)
665            } else {
666                Ok((object, resolve))
667            }
668        })
669    }
670
671    fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
672        Box::pin(async {
673            let (data, resolve) = self.fetch_bytes().await?;
674            let object = T::parse_slice_extra(&data, &resolve, &self.extra)?;
675            if self.inner.address.hash != object.full_hash() {
676                Err(Error::DataMismatch)
677            } else {
678                Ok(object)
679            }
680        })
681    }
682}
683
684pub trait PointVisitor {
685    fn visit<T: Traversible>(&mut self, point: &Point<T>);
686}
687
688struct HashVisitor<F>(F);
689
690impl<F: FnMut(Hash)> PointVisitor for HashVisitor<F> {
691    fn visit<T: Traversible>(&mut self, point: &Point<T>) {
692        self.0(point.hash());
693    }
694}
695
696pub struct ReflessInput<'a> {
697    data: Option<&'a [u8]>,
698}
699
700pub struct Input<'a, Extra = ()> {
701    refless: ReflessInput<'a>,
702    resolve: &'a Arc<dyn Resolve>,
703    index: &'a Cell<usize>,
704    extra: &'a Extra,
705}
706
707impl<'a, Extra> Deref for Input<'a, Extra> {
708    type Target = ReflessInput<'a>;
709
710    fn deref(&self) -> &Self::Target {
711        &self.refless
712    }
713}
714
715impl<Extra> DerefMut for Input<'_, Extra> {
716    fn deref_mut(&mut self) -> &mut Self::Target {
717        &mut self.refless
718    }
719}
720
721impl<'a, Extra> Input<'a, Extra> {
722    pub fn replace_extra<E>(self, extra: &'a E) -> Input<'a, E> {
723        Input {
724            refless: self.refless,
725            resolve: self.resolve,
726            index: self.index,
727            extra,
728        }
729    }
730}
731
732impl<'a> ReflessInput<'a> {
733    fn data(&self) -> crate::Result<&'a [u8]> {
734        self.data.ok_or(Error::EndOfInput)
735    }
736
737    fn make_error<T>(&mut self, e: crate::Error) -> crate::Result<T> {
738        self.data = None;
739        Err(e)
740    }
741
742    fn end_of_input<T>(&mut self) -> crate::Result<T> {
743        self.make_error(Error::EndOfInput)
744    }
745}
746
747impl ParseInput for ReflessInput<'_> {
748    fn parse_chunk<'a, const N: usize>(&mut self) -> crate::Result<&'a [u8; N]>
749    where
750        Self: 'a,
751    {
752        match self.data()?.split_first_chunk() {
753            Some((chunk, data)) => {
754                self.data = Some(data);
755                Ok(chunk)
756            }
757            None => self.end_of_input(),
758        }
759    }
760
761    fn parse_n<'a>(&mut self, n: usize) -> crate::Result<&'a [u8]>
762    where
763        Self: 'a,
764    {
765        match self.data()?.split_at_checked(n) {
766            Some((chunk, data)) => {
767                self.data = Some(data);
768                Ok(chunk)
769            }
770            None => self.end_of_input(),
771        }
772    }
773
774    fn parse_ahead<T: Parse<Self>>(&mut self, n: usize) -> crate::Result<T> {
775        let input = ReflessInput {
776            data: Some(self.parse_n(n)?),
777        };
778        T::parse(input)
779    }
780
781    fn parse_compare<T: ParseInline<Self>>(&mut self, n: usize, c: &[u8]) -> Result<Option<T>> {
782        match self.data()?.split_at_checked(n) {
783            Some((chunk, data)) => {
784                if chunk == c {
785                    self.data = Some(data);
786                    Ok(None)
787                } else {
788                    self.parse_inline().map(Some)
789                }
790            }
791            None => self.end_of_input(),
792        }
793    }
794
795    fn parse_all<'a>(self) -> crate::Result<&'a [u8]>
796    where
797        Self: 'a,
798    {
799        self.data()
800    }
801
802    fn empty(self) -> crate::Result<()> {
803        if self.data()?.is_empty() {
804            Ok(())
805        } else {
806            Err(Error::ExtraInputLeft)
807        }
808    }
809
810    fn non_empty(self) -> crate::Result<Option<Self>> {
811        Ok(if self.data()?.is_empty() {
812            None
813        } else {
814            Some(self)
815        })
816    }
817}
818
819impl<Extra> ParseInput for Input<'_, Extra> {
820    fn parse_chunk<'a, const N: usize>(&mut self) -> crate::Result<&'a [u8; N]>
821    where
822        Self: 'a,
823    {
824        (**self).parse_chunk()
825    }
826
827    fn parse_n<'a>(&mut self, n: usize) -> crate::Result<&'a [u8]>
828    where
829        Self: 'a,
830    {
831        (**self).parse_n(n)
832    }
833
834    fn parse_ahead<T: Parse<Self>>(&mut self, n: usize) -> crate::Result<T> {
835        let input = Input {
836            refless: ReflessInput {
837                data: Some(self.parse_n(n)?),
838            },
839            resolve: self.resolve,
840            index: self.index,
841            extra: self.extra,
842        };
843        T::parse(input)
844    }
845
846    fn parse_compare<T: ParseInline<Self>>(&mut self, n: usize, c: &[u8]) -> Result<Option<T>> {
847        match self.data()?.split_at_checked(n) {
848            Some((chunk, data)) => {
849                if chunk == c {
850                    self.data = Some(data);
851                    Ok(None)
852                } else {
853                    self.parse_inline().map(Some)
854                }
855            }
856            None => self.end_of_input(),
857        }
858    }
859
860    fn parse_all<'a>(self) -> crate::Result<&'a [u8]>
861    where
862        Self: 'a,
863    {
864        self.refless.parse_all()
865    }
866
867    fn empty(self) -> crate::Result<()> {
868        self.refless.empty()
869    }
870
871    fn non_empty(mut self) -> crate::Result<Option<Self>> {
872        self.refless = match self.refless.non_empty()? {
873            Some(refless) => refless,
874            None => return Ok(None),
875        };
876        Ok(Some(self))
877    }
878}
879
880impl<'a, Extra: 'static + Clone> PointInput for Input<'a, Extra> {
881    type Extra = Extra;
882    type WithExtra<E: 'static + Clone> = Input<'a, E>;
883
884    fn next_index(&mut self) -> usize {
885        let index = self.index.get();
886        self.index.set(index + 1);
887        index
888    }
889
890    fn resolve_arc_ref(&self) -> &Arc<dyn Resolve> {
891        self.resolve
892    }
893
894    fn extra(&self) -> &Self::Extra {
895        self.extra
896    }
897
898    fn map_extra<E: 'static + Clone>(
899        self,
900        f: impl FnOnce(&Self::Extra) -> &E,
901    ) -> Self::WithExtra<E> {
902        let Self {
903            refless,
904            resolve,
905            index,
906            extra,
907        } = self;
908        Input {
909            refless,
910            resolve,
911            index,
912            extra: f(extra),
913        }
914    }
915}
916
917pub trait ToOutput {
918    fn to_output(&self, output: &mut dyn Output);
919
920    fn data_hash(&self) -> Hash {
921        let mut output = HashOutput::default();
922        self.to_output(&mut output);
923        output.hash()
924    }
925
926    fn slice_to_output(slice: &[Self], output: &mut dyn Output)
927    where
928        Self: Sized,
929    {
930        slice.iter_to_output(output);
931    }
932
933    fn output<T: Output + Default>(&self) -> T {
934        let mut output = T::default();
935        self.to_output(&mut output);
936        output
937    }
938
939    fn vec(&self) -> Vec<u8> {
940        self.output()
941    }
942}
943
944#[derive(Default)]
945struct CountVisitor {
946    count: usize,
947}
948
949impl PointVisitor for CountVisitor {
950    fn visit<T: Traversible>(&mut self, _: &Point<T>) {
951        self.count += 1;
952    }
953}
954
955pub trait Topological {
956    fn accept_points(&self, visitor: &mut impl PointVisitor) {
957        let _ = visitor;
958    }
959
960    fn topology_hash(&self) -> Hash {
961        let mut hasher = Sha256::new();
962        self.accept_points(&mut HashVisitor(|hash| hasher.update(hash)));
963        Hash::from_sha256(hasher.finalize().into())
964    }
965
966    fn point_count(&self) -> usize {
967        let mut visitor = CountVisitor::default();
968        self.accept_points(&mut visitor);
969        visitor.count
970    }
971
972    fn topology(&self) -> TopoVec {
973        let mut topology = TopoVec::with_capacity(self.point_count());
974        self.accept_points(&mut topology);
975        topology
976    }
977}
978
979pub trait Tagged {
980    const TAGS: Tags = Tags(&[], &[]);
981
982    const HASH: Hash =
983        const { Hash::from_sha256(Self::TAGS.const_hash(sha2_const::Sha256::new()).finalize()) };
984}
985
986pub trait ParseSlice: for<'a> Parse<Input<'a>> {
987    fn parse_slice(data: &[u8], resolve: &Arc<dyn Resolve>) -> crate::Result<Self> {
988        Self::parse_slice_extra(data, resolve, &())
989    }
990}
991
992impl<T: for<'a> Parse<Input<'a>>> ParseSlice for T {}
993
994pub trait ParseSliceExtra<Extra>: for<'a> Parse<Input<'a, Extra>> {
995    fn parse_slice_extra(
996        data: &[u8],
997        resolve: &Arc<dyn Resolve>,
998        extra: &Extra,
999    ) -> crate::Result<Self> {
1000        let input = Input {
1001            refless: ReflessInput { data: Some(data) },
1002            resolve,
1003            index: &Cell::new(0),
1004            extra,
1005        };
1006        let object = Self::parse(input)?;
1007        Ok(object)
1008    }
1009}
1010
1011impl<T: for<'a> Parse<Input<'a, Extra>>, Extra> ParseSliceExtra<Extra> for T {}
1012
1013#[derive(ToOutput)]
1014pub struct ObjectHashes {
1015    pub tags: Hash,
1016    pub topology: Hash,
1017    pub data: Hash,
1018}
1019
1020pub trait FullHash: ToOutput + Topological + Tagged {
1021    fn hashes(&self) -> ObjectHashes {
1022        ObjectHashes {
1023            tags: Self::HASH,
1024            topology: self.topology_hash(),
1025            data: self.data_hash(),
1026        }
1027    }
1028
1029    fn full_hash(&self) -> Hash {
1030        self.hashes().data_hash()
1031    }
1032}
1033
1034impl<T: ?Sized + ToOutput + Topological + Tagged> FullHash for T {}
1035
1036pub trait Traversible: 'static + Sized + Send + Sync + FullHash {
1037    fn to_resolve(&self) -> Arc<dyn Resolve> {
1038        Arc::new(ByTopology {
1039            topology: self.topology(),
1040        })
1041    }
1042
1043    fn point(self) -> Point<Self>
1044    where
1045        Self: Clone,
1046    {
1047        Point::from_object(self)
1048    }
1049}
1050
1051impl<T: 'static + Send + Sync + FullHash> Traversible for T {}
1052
1053pub trait Object<Extra: 'static = ()>: Traversible + for<'a> Parse<Input<'a, Extra>> {}
1054
1055pub struct Tags(pub &'static [&'static str], pub &'static [&'static Self]);
1056
1057impl Tags {
1058    const fn const_hash(&self, mut hasher: sha2_const::Sha256) -> sha2_const::Sha256 {
1059        {
1060            let mut i = 0;
1061            while i < self.0.len() {
1062                hasher = hasher.update(self.0[i].as_bytes());
1063                i += 1;
1064            }
1065        }
1066        {
1067            let mut i = 0;
1068            while i < self.1.len() {
1069                hasher = self.1[i].const_hash(hasher);
1070                i += 1;
1071            }
1072        }
1073        hasher
1074    }
1075}
1076
1077pub trait Inline<Extra: 'static = ()>:
1078    Object<Extra> + for<'a> ParseInline<Input<'a, Extra>>
1079{
1080}
1081
1082impl<T: Traversible> Topological for Point<T> {
1083    fn accept_points(&self, visitor: &mut impl PointVisitor) {
1084        visitor.visit(self);
1085    }
1086
1087    fn point_count(&self) -> usize {
1088        1
1089    }
1090}
1091
1092impl<T: Object<I::Extra>, I: PointInput<Extra: Send + Sync>> ParseInline<I> for Point<T> {
1093    fn parse_inline(input: &mut I) -> crate::Result<Self> {
1094        Ok(Self::from_address_extra(
1095            input.parse_inline()?,
1096            input.resolve(),
1097            input.extra().clone(),
1098        ))
1099    }
1100}
1101
1102impl<T: Tagged> Tagged for Point<T> {
1103    const TAGS: Tags = T::TAGS;
1104}
1105
1106impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Object<Extra> for Point<T> {}
1107
1108impl<T> ToOutput for Point<T> {
1109    fn to_output(&self, output: &mut dyn Output) {
1110        self.hash().to_output(output);
1111    }
1112}
1113
1114impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Inline<Extra> for Point<T> {}
1115
1116pub trait Topology: Send + Sync {
1117    fn len(&self) -> usize;
1118    fn get(&self, index: usize) -> Option<&Arc<dyn Singular>>;
1119
1120    fn is_empty(&self) -> bool {
1121        self.len() == 0
1122    }
1123}
1124
1125pub trait Singular: Send + Sync + FetchBytes {
1126    fn hash(&self) -> Hash;
1127}
1128
1129pub type TopoVec = Vec<Arc<dyn Singular>>;
1130
1131impl PointVisitor for TopoVec {
1132    fn visit<T: Traversible>(&mut self, point: &Point<T>) {
1133        self.push(Arc::new(point.clone()));
1134    }
1135}
1136
1137impl<T> FetchBytes for Point<T> {
1138    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
1139        self.origin.fetch_bytes()
1140    }
1141
1142    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
1143        self.origin.fetch_data()
1144    }
1145}
1146
1147impl<T> Singular for Point<T> {
1148    fn hash(&self) -> Hash {
1149        self.hash.unwrap()
1150    }
1151}
1152
1153impl Topology for TopoVec {
1154    fn len(&self) -> usize {
1155        self.len()
1156    }
1157
1158    fn get(&self, index: usize) -> Option<&Arc<dyn Singular>> {
1159        (**self).get(index)
1160    }
1161}
1162
1163pub trait ParseSliceRefless: for<'a> Parse<ReflessInput<'a>> {
1164    fn parse_slice_refless(data: &[u8]) -> crate::Result<Self> {
1165        let input = ReflessInput { data: Some(data) };
1166        let object = Self::parse(input)?;
1167        Ok(object)
1168    }
1169}
1170
1171impl<T: for<'a> Parse<ReflessInput<'a>>> ParseSliceRefless for T {}
1172
1173pub trait ReflessObject:
1174    'static + Sized + Send + Sync + ToOutput + Tagged + for<'a> Parse<ReflessInput<'a>>
1175{
1176}
1177
1178pub trait ReflessInline: ReflessObject + for<'a> ParseInline<ReflessInput<'a>> {
1179    fn parse_as_inline(mut input: ReflessInput) -> crate::Result<Self> {
1180        let object = Self::parse_inline(&mut input)?;
1181        input.empty()?;
1182        Ok(object)
1183    }
1184}
1185
1186pub trait Output {
1187    fn write(&mut self, data: &[u8]);
1188}
1189
1190impl Output for Vec<u8> {
1191    fn write(&mut self, data: &[u8]) {
1192        self.extend_from_slice(data);
1193    }
1194}
1195
1196impl Output for Vec<&'static str> {
1197    fn write(&mut self, data: &[u8]) {
1198        let _ = data;
1199    }
1200}
1201
1202#[derive(Default)]
1203struct HashOutput {
1204    hasher: Sha256,
1205    at: usize,
1206}
1207
1208impl Output for HashOutput {
1209    fn write(&mut self, data: &[u8]) {
1210        self.hasher.update(data);
1211        self.at += data.len();
1212    }
1213}
1214
1215impl HashOutput {
1216    fn hash(self) -> Hash {
1217        Hash::from_sha256(self.hasher.finalize().into())
1218    }
1219}
1220
1221pub struct PointMut<'a, T: FullHash> {
1222    hash: &'a mut OptionalHash,
1223    origin: &'a mut dyn Fetch<T = T>,
1224}
1225
1226impl<T: FullHash> Deref for PointMut<'_, T> {
1227    type Target = T;
1228
1229    fn deref(&self) -> &Self::Target {
1230        self.origin.get().unwrap()
1231    }
1232}
1233
1234impl<T: FullHash> DerefMut for PointMut<'_, T> {
1235    fn deref_mut(&mut self) -> &mut Self::Target {
1236        self.origin.get_mut().unwrap()
1237    }
1238}
1239
1240impl<T: FullHash> Drop for PointMut<'_, T> {
1241    fn drop(&mut self) {
1242        self.finalize();
1243    }
1244}
1245
1246impl<'a, T: FullHash> PointMut<'a, T> {
1247    fn finalize(&mut self) {
1248        self.origin.get_mut_finalize();
1249        *self.hash = self.full_hash().into();
1250    }
1251}
1252
1253impl<T: Traversible + Clone> Point<T> {
1254    pub fn from_object(object: T) -> Self {
1255        Self::from_origin(object.full_hash(), Arc::new(LocalOrigin { object }))
1256    }
1257
1258    fn yolo_mut(&mut self) -> bool {
1259        self.origin.get().is_some()
1260            && Arc::get_mut(&mut self.origin).is_some_and(|origin| origin.get_mut().is_some())
1261    }
1262
1263    async fn prepare_yolo_origin(&mut self) -> crate::Result<()> {
1264        if !self.yolo_mut() {
1265            let object = self.origin.fetch().await?;
1266            self.origin = Arc::new(LocalOrigin { object });
1267        }
1268        Ok(())
1269    }
1270
1271    pub async fn fetch_mut(&'_ mut self) -> crate::Result<PointMut<'_, T>> {
1272        self.prepare_yolo_origin().await?;
1273        let origin = Arc::get_mut(&mut self.origin).unwrap();
1274        assert!(origin.get_mut().is_some());
1275        self.hash.clear();
1276        Ok(PointMut {
1277            hash: &mut self.hash,
1278            origin,
1279        })
1280    }
1281
1282    pub async fn fetch_ref<Extra: 'static + Send + Sync + Clone>(&mut self) -> crate::Result<&T>
1283    where
1284        T: Object<Extra> + Clone,
1285    {
1286        self.prepare_yolo_origin().await?;
1287        Ok(self.origin.get().unwrap())
1288    }
1289}
1290
1291struct LocalOrigin<T> {
1292    object: T,
1293}
1294
1295impl<T> Deref for LocalOrigin<T> {
1296    type Target = T;
1297
1298    fn deref(&self) -> &Self::Target {
1299        &self.object
1300    }
1301}
1302
1303impl<T> DerefMut for LocalOrigin<T> {
1304    fn deref_mut(&mut self) -> &mut Self::Target {
1305        &mut self.object
1306    }
1307}
1308
1309impl<T: Traversible + Clone> Fetch for LocalOrigin<T> {
1310    type T = T;
1311
1312    fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
1313        Box::pin(ready(Ok((self.object.clone(), self.object.to_resolve()))))
1314    }
1315
1316    fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
1317        Box::pin(ready(Ok(self.object.clone())))
1318    }
1319
1320    fn get(&self) -> Option<&Self::T> {
1321        Some(self)
1322    }
1323
1324    fn get_mut(&mut self) -> Option<&mut Self::T> {
1325        Some(self)
1326    }
1327}
1328
1329impl<T: Traversible + Clone> FetchBytes for LocalOrigin<T> {
1330    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
1331        Box::pin(ready(Ok((self.object.output(), self.object.to_resolve()))))
1332    }
1333
1334    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
1335        Box::pin(ready(Ok(self.object.output())))
1336    }
1337}
1338
1339struct ByTopology {
1340    topology: TopoVec,
1341}
1342
1343impl ByTopology {
1344    fn try_resolve(&'_ self, address: Address) -> Result<FailFuture<'_, ByteNode>> {
1345        let point = self
1346            .topology
1347            .get(address.index)
1348            .ok_or(Error::AddressOutOfBounds)?;
1349        if point.hash() != address.hash {
1350            Err(Error::ResolutionMismatch)
1351        } else {
1352            Ok(point.fetch_bytes())
1353        }
1354    }
1355
1356    fn try_resolve_data(&'_ self, address: Address) -> Result<FailFuture<'_, Vec<u8>>> {
1357        let point = self
1358            .topology
1359            .get(address.index)
1360            .ok_or(Error::AddressOutOfBounds)?;
1361        if point.hash() != address.hash {
1362            Err(Error::ResolutionMismatch)
1363        } else {
1364            Ok(point.fetch_data())
1365        }
1366    }
1367}
1368
1369impl Resolve for ByTopology {
1370    fn resolve(&'_ self, address: Address) -> FailFuture<'_, ByteNode> {
1371        self.try_resolve(address)
1372            .map_err(Err)
1373            .map_err(ready)
1374            .map_err(Box::pin)
1375            .unwrap_or_else(|x| x)
1376    }
1377
1378    fn resolve_data(&'_ self, address: Address) -> FailFuture<'_, Vec<u8>> {
1379        self.try_resolve_data(address)
1380            .map_err(Err)
1381            .map_err(ready)
1382            .map_err(Box::pin)
1383            .unwrap_or_else(|x| x)
1384    }
1385
1386    fn name(&self) -> &str {
1387        "by topology"
1388    }
1389}
1390
1391impl<T: FullHash> Fetch for Point<T> {
1392    type T = T;
1393
1394    fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
1395        self.origin.fetch_full()
1396    }
1397
1398    fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
1399        self.origin.fetch()
1400    }
1401
1402    fn get(&self) -> Option<&Self::T> {
1403        self.origin.get()
1404    }
1405
1406    fn get_mut(&mut self) -> Option<&mut Self::T> {
1407        self.hash.clear();
1408        Arc::get_mut(&mut self.origin)?.get_mut()
1409    }
1410
1411    fn get_mut_finalize(&mut self) {
1412        let origin = Arc::get_mut(&mut self.origin).unwrap();
1413        origin.get_mut_finalize();
1414        self.hash = origin.get().unwrap().full_hash().into();
1415    }
1416}
1417
1418pub trait Size {
1419    const SIZE: usize = <Self::Size as Unsigned>::USIZE;
1420    type Size: Unsigned;
1421}
1422
1423pub trait SizeExt: Size<Size: ArrayLength> + ToOutput {
1424    fn to_array(&self) -> GenericArray<u8, Self::Size> {
1425        let mut array = GenericArray::default();
1426        let mut output = ArrayOutput {
1427            data: &mut array,
1428            offset: 0,
1429        };
1430        self.to_output(&mut output);
1431        output.finalize();
1432        array
1433    }
1434}
1435
1436impl<T: Size<Size: ArrayLength> + ToOutput> SizeExt for T {}
1437
1438struct ArrayOutput<'a> {
1439    data: &'a mut [u8],
1440    offset: usize,
1441}
1442
1443impl ArrayOutput<'_> {
1444    fn finalize(self) {
1445        assert_eq!(self.offset, self.data.len());
1446    }
1447}
1448
1449impl Output for ArrayOutput<'_> {
1450    fn write(&mut self, data: &[u8]) {
1451        self.data[self.offset..][..data.len()].copy_from_slice(data);
1452        self.offset += data.len();
1453    }
1454}
1455
1456trait RainbowIterator: Sized + IntoIterator {
1457    fn iter_to_output(self, output: &mut dyn Output)
1458    where
1459        Self::Item: ToOutput,
1460    {
1461        self.into_iter().for_each(|item| item.to_output(output));
1462    }
1463
1464    fn iter_accept_points(self, visitor: &mut impl PointVisitor)
1465    where
1466        Self::Item: Topological,
1467    {
1468        self.into_iter()
1469            .for_each(|item| item.accept_points(visitor));
1470    }
1471}
1472
1473pub trait ParseInput: Sized {
1474    fn parse_chunk<'a, const N: usize>(&mut self) -> crate::Result<&'a [u8; N]>
1475    where
1476        Self: 'a;
1477    fn parse_n<'a>(&mut self, n: usize) -> crate::Result<&'a [u8]>
1478    where
1479        Self: 'a;
1480    fn parse_ahead<T: Parse<Self>>(&mut self, n: usize) -> crate::Result<T>;
1481    fn parse_compare<T: ParseInline<Self>>(&mut self, n: usize, c: &[u8]) -> Result<Option<T>>;
1482    fn parse_all<'a>(self) -> crate::Result<&'a [u8]>
1483    where
1484        Self: 'a;
1485    fn empty(self) -> crate::Result<()>;
1486    fn non_empty(self) -> crate::Result<Option<Self>>;
1487
1488    fn consume(self, f: impl FnMut(&mut Self) -> crate::Result<()>) -> crate::Result<()> {
1489        self.collect(f)
1490    }
1491
1492    fn parse_collect<T: ParseInline<Self>, B: FromIterator<T>>(self) -> crate::Result<B> {
1493        self.collect(|input| input.parse_inline())
1494    }
1495
1496    fn collect<T, B: FromIterator<T>>(
1497        self,
1498        f: impl FnMut(&mut Self) -> crate::Result<T>,
1499    ) -> crate::Result<B> {
1500        self.iter(f).collect()
1501    }
1502
1503    fn iter<T>(
1504        self,
1505        mut f: impl FnMut(&mut Self) -> crate::Result<T>,
1506    ) -> impl Iterator<Item = crate::Result<T>> {
1507        let mut state = Some(self);
1508        std::iter::from_fn(move || {
1509            let mut input = match state.take()?.non_empty() {
1510                Ok(input) => input,
1511                Err(e) => return Some(Err(e)),
1512            }?;
1513            let item = f(&mut input);
1514            state = Some(input);
1515            Some(item)
1516        })
1517    }
1518
1519    fn parse_inline<T: ParseInline<Self>>(&mut self) -> crate::Result<T> {
1520        T::parse_inline(self)
1521    }
1522
1523    fn parse<T: Parse<Self>>(self) -> crate::Result<T> {
1524        T::parse(self)
1525    }
1526
1527    fn parse_vec<T: ParseInline<Self>>(self) -> crate::Result<Vec<T>> {
1528        T::parse_vec(self)
1529    }
1530}
1531
1532pub trait PointInput: ParseInput {
1533    type Extra: 'static + Clone;
1534    type WithExtra<E: 'static + Clone>: PointInput<Extra = E, WithExtra<Self::Extra> = Self>;
1535    fn next_index(&mut self) -> usize;
1536    fn resolve_arc_ref(&self) -> &Arc<dyn Resolve>;
1537    fn resolve(&self) -> Arc<dyn Resolve> {
1538        self.resolve_arc_ref().clone()
1539    }
1540    fn resolve_ref(&self) -> &dyn Resolve {
1541        self.resolve_arc_ref().as_ref()
1542    }
1543    fn extension<T: Any>(&self) -> crate::Result<&T> {
1544        self.resolve_ref()
1545            .extension(TypeId::of::<T>())?
1546            .downcast_ref()
1547            .ok_or(Error::ExtensionType)
1548    }
1549    fn extra(&self) -> &Self::Extra;
1550    fn map_extra<E: 'static + Clone>(
1551        self,
1552        f: impl FnOnce(&Self::Extra) -> &E,
1553    ) -> Self::WithExtra<E>;
1554}
1555
1556impl<T: Sized + IntoIterator> RainbowIterator for T {}
1557
1558pub trait Parse<I: ParseInput>: Sized {
1559    fn parse(input: I) -> crate::Result<Self>;
1560}
1561
1562pub trait ParseInline<I: ParseInput>: Parse<I> {
1563    fn parse_inline(input: &mut I) -> crate::Result<Self>;
1564    fn parse_as_inline(mut input: I) -> crate::Result<Self> {
1565        let object = Self::parse_inline(&mut input)?;
1566        input.empty()?;
1567        Ok(object)
1568    }
1569    fn parse_vec(input: I) -> crate::Result<Vec<Self>> {
1570        input.parse_collect()
1571    }
1572}
1573
1574/// Implemented if both types have the exact same layout.
1575/// This implies having the same [`MaybeHasNiche::MnArray`].
1576///
1577/// This is represented as two-way conversion for two reasons:
1578/// - to highlight that the conversion is actual equivalence
1579/// - to increase flexibility (mostly to go around the orphan rule)
1580pub trait Equivalent<T>: Sized {
1581    /// Inverse of [`Equivalent::from_equivalent`].
1582    fn into_equivalent(self) -> T;
1583    /// Inverse of [`Equivalent::into_equivalent`].
1584    fn from_equivalent(object: T) -> Self;
1585}
1586
1587/// This implementation is the main goal of [`Equivalent`]: we assume transmuting the pointer is
1588/// safe.
1589impl<U: 'static + Equivalent<T>, T: 'static> Equivalent<Point<T>> for Point<U> {
1590    fn into_equivalent(self) -> Point<T> {
1591        self.map_origin(|origin| {
1592            Arc::new(MapEquivalent {
1593                origin,
1594                map: U::into_equivalent,
1595            })
1596        })
1597    }
1598
1599    fn from_equivalent(point: Point<T>) -> Self {
1600        point.map_origin(|origin| {
1601            Arc::new(MapEquivalent {
1602                origin,
1603                map: U::from_equivalent,
1604            })
1605        })
1606    }
1607}
1608
1609struct MapEquivalent<T, F> {
1610    origin: Arc<dyn Fetch<T = T>>,
1611    map: F,
1612}
1613
1614impl<T, F> FetchBytes for MapEquivalent<T, F> {
1615    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
1616        self.origin.fetch_bytes()
1617    }
1618
1619    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
1620        self.origin.fetch_data()
1621    }
1622}
1623
1624trait Map1<T>: Fn(T) -> Self::U {
1625    type U;
1626}
1627
1628impl<T, U, F: Fn(T) -> U> Map1<T> for F {
1629    type U = U;
1630}
1631
1632impl<T, F: 'static + Send + Sync + Map1<T>> Fetch for MapEquivalent<T, F> {
1633    type T = F::U;
1634
1635    fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
1636        Box::pin(self.origin.fetch_full().map_ok(|(x, r)| ((self.map)(x), r)))
1637    }
1638
1639    fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
1640        Box::pin(self.origin.fetch().map_ok(&self.map))
1641    }
1642}
1643
1644impl<T: 'static + ToOutput> Point<T> {
1645    pub fn map<U>(self, map: impl 'static + Send + Sync + Fn(T) -> U) -> Point<U> {
1646        self.map_origin(|origin| Arc::new(Map { origin, map }))
1647    }
1648}
1649
1650struct Map<T, F> {
1651    origin: Arc<dyn Fetch<T = T>>,
1652    map: F,
1653}
1654
1655impl<T: ToOutput, F> FetchBytes for Map<T, F> {
1656    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
1657        Box::pin(self.origin.fetch_full().map_ok(|(x, r)| (x.output(), r)))
1658    }
1659
1660    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
1661        Box::pin(self.origin.fetch().map_ok(|x| x.output()))
1662    }
1663}
1664
1665impl<T: ToOutput, F: 'static + Send + Sync + Map1<T>> Fetch for Map<T, F> {
1666    type T = F::U;
1667
1668    fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
1669        Box::pin(self.origin.fetch_full().map_ok(|(x, r)| ((self.map)(x), r)))
1670    }
1671
1672    fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
1673        Box::pin(self.origin.fetch().map_ok(&self.map))
1674    }
1675}
1676
1677impl<T> MaybeHasNiche for Point<T> {
1678    type MnArray = <Hash as MaybeHasNiche>::MnArray;
1679}
1680
1681impl<T: FullHash + Default> Point<T> {
1682    pub fn is_default(&self) -> bool {
1683        self.hash() == T::default().full_hash()
1684    }
1685}
1686
1687impl<T: Default + Traversible + Clone> Default for Point<T> {
1688    fn default() -> Self {
1689        T::default().point()
1690    }
1691}
1692
1693#[test]
1694fn options() {
1695    type T0 = ();
1696    type T1 = Option<T0>;
1697    type T2 = Option<T1>;
1698    type T3 = Option<T2>;
1699    type T4 = Option<T3>;
1700    type T5 = Option<T4>;
1701    assert_eq!(T0::SIZE, 0);
1702    assert_eq!(T1::SIZE, 1);
1703    assert_eq!(T2::SIZE, 1);
1704    assert_eq!(T3::SIZE, 1);
1705    assert_eq!(T4::SIZE, 1);
1706    assert_eq!(T5::SIZE, 1);
1707    assert_eq!(Some(Some(Some(()))).vec(), [0]);
1708    assert_eq!(Some(Some(None::<()>)).vec(), [1]);
1709    assert_eq!(Some(None::<Option<()>>).vec(), [2]);
1710    assert_eq!(None::<Option<Option<()>>>.vec(), [3]);
1711
1712    assert_eq!(false.vec(), [0]);
1713    assert_eq!(true.vec(), [1]);
1714    assert_eq!(Some(false).vec(), [0]);
1715    assert_eq!(Some(true).vec(), [1]);
1716    assert_eq!(None::<bool>.vec(), [2]);
1717    assert_eq!(Some(Some(false)).vec(), [0]);
1718    assert_eq!(Some(Some(true)).vec(), [1]);
1719    assert_eq!(Some(None::<bool>).vec(), [2]);
1720    assert_eq!(None::<Option<bool>>.vec(), [3]);
1721    assert_eq!(Some(Some(Some(false))).vec(), [0]);
1722    assert_eq!(Some(Some(Some(true))).vec(), [1]);
1723    assert_eq!(Some(Some(None::<bool>)).vec(), [2]);
1724    assert_eq!(Some(None::<Option<bool>>).vec(), [3]);
1725    assert_eq!(None::<Option<Option<bool>>>.vec(), [4]);
1726    assert_eq!(Option::<Point<()>>::SIZE, HASH_SIZE);
1727    assert_eq!(Some(()).vec(), [0]);
1728    assert_eq!(Some(((), ())).vec(), [0]);
1729    assert_eq!(Some(((), true)).vec(), [1]);
1730    assert_eq!(Some((true, true)).vec(), [1, 1]);
1731    assert_eq!(Some((Some(true), true)).vec(), [1, 1]);
1732    assert_eq!(Some((None::<bool>, true)).vec(), [2, 1]);
1733    assert_eq!(Some((true, None::<bool>)).vec(), [1, 2]);
1734    assert_eq!(None::<(Option<bool>, bool)>.vec(), [3, 2]);
1735    assert_eq!(None::<(bool, Option<bool>)>.vec(), [2, 3]);
1736    assert_eq!(Some(Some((Some(true), Some(true)))).vec(), [1, 1],);
1737    assert_eq!(Option::<Point<()>>::SIZE, HASH_SIZE);
1738    assert_eq!(Option::<Option<Point<()>>>::SIZE, HASH_SIZE);
1739    assert_eq!(Option::<Option<Option<Point<()>>>>::SIZE, HASH_SIZE);
1740}