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> Default for ObjectMarker<T> {
338    fn default() -> Self {
339        Self {
340            object: Default::default(),
341        }
342    }
343}
344
345impl<T: ?Sized + Tagged> Tagged for ObjectMarker<T> {}
346impl<T: ?Sized + 'static + Tagged, Extra: 'static> Object<Extra> for ObjectMarker<T> {}
347impl<T: ?Sized + 'static + Tagged, Extra: 'static> Inline<Extra> for ObjectMarker<T> {}
348
349#[derive(Clone, ParseAsInline)]
350struct Extras<Extra>(Extra);
351
352impl<Extra> Deref for Extras<Extra> {
353    type Target = Extra;
354
355    fn deref(&self) -> &Self::Target {
356        &self.0
357    }
358}
359
360impl<Extra> ToOutput for Extras<Extra> {
361    fn to_output(&self, _: &mut dyn Output) {}
362}
363
364impl<I: PointInput> ParseInline<I> for Extras<I::Extra> {
365    fn parse_inline(input: &mut I) -> crate::Result<Self> {
366        Ok(Self(input.extra().clone()))
367    }
368}
369
370impl<Extra> Tagged for Extras<Extra> {}
371impl<Extra> Topological for Extras<Extra> {}
372impl<Extra: 'static + Send + Sync + Clone> Object<Extra> for Extras<Extra> {}
373impl<Extra: 'static + Send + Sync + Clone> Inline<Extra> for Extras<Extra> {}
374
375#[derive(ToOutput, Tagged, Parse, ParseInline)]
376pub struct RawPoint<T = Infallible, Extra = ()> {
377    inner: RawPointInner,
378    extra: Extras<Extra>,
379    object: ObjectMarker<T>,
380}
381
382impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Topological for RawPoint<T, Extra> {
383    fn accept_points(&self, visitor: &mut impl PointVisitor) {
384        visitor.visit(&self.clone().point());
385    }
386
387    fn point_count(&self) -> usize {
388        1
389    }
390}
391
392impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Object<Extra> for RawPoint<T, Extra> {}
393impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Inline<Extra> for RawPoint<T, Extra> {}
394
395impl<T, Extra: 'static + Clone> FromInner for RawPoint<T, Extra> {
396    type Inner = RawPointInner;
397    type Extra = Extra;
398
399    fn from_inner(inner: Self::Inner, extra: Self::Extra) -> Self {
400        RawPoint {
401            inner,
402            extra: Extras(extra),
403            object: Default::default(),
404        }
405    }
406}
407
408impl<T, Extra: Clone> Clone for RawPoint<T, Extra> {
409    fn clone(&self) -> Self {
410        Self {
411            inner: self.inner.clone(),
412            extra: self.extra.clone(),
413            object: Default::default(),
414        }
415    }
416}
417
418impl<T> Point<T> {
419    pub fn raw<Extra: 'static + Clone>(self, extra: Extra) -> RawPoint<T, Extra> {
420        {
421            if let Some(raw) = self.origin.inner_cast(&extra) {
422                return raw;
423            }
424        }
425        RawPointInner {
426            hash: self.hash.unwrap(),
427            origin: self.origin,
428        }
429        .cast(extra)
430    }
431}
432
433impl<T, Extra: 'static + Clone> RawPoint<T, Extra> {
434    pub fn cast<U>(self) -> RawPoint<U, Extra> {
435        self.inner.cast(self.extra.0)
436    }
437}
438
439impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> RawPoint<T, Extra> {
440    pub fn point(self) -> Point<T> {
441        Point::from_origin(self.inner.hash, Arc::new(self))
442    }
443}
444
445impl FetchBytes for RawPointInner {
446    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
447        self.origin.fetch_bytes()
448    }
449
450    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
451        self.origin.fetch_data()
452    }
453}
454
455impl<T, Extra: 'static> FetchBytes for RawPoint<T, Extra> {
456    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
457        self.inner.fetch_bytes()
458    }
459
460    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
461        self.inner.fetch_data()
462    }
463
464    fn as_inner(&self) -> Option<&dyn Any> {
465        Some(&self.inner)
466    }
467}
468
469impl<T: Object<Extra>, Extra: 'static + Send + Sync> Fetch for RawPoint<T, Extra> {
470    type T = T;
471
472    fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
473        Box::pin(async {
474            let (data, resolve) = self.inner.origin.fetch_bytes().await?;
475            let object = T::parse_slice_extra(&data, &resolve, &self.extra)?;
476            if self.inner.hash != object.full_hash() {
477                Err(Error::DataMismatch)
478            } else {
479                Ok((object, resolve))
480            }
481        })
482    }
483
484    fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
485        Box::pin(async {
486            let (data, resolve) = self.inner.origin.fetch_bytes().await?;
487            let object = T::parse_slice_extra(&data, &resolve, &self.extra)?;
488            if self.inner.hash != object.full_hash() {
489                Err(Error::DataMismatch)
490            } else {
491                Ok(object)
492            }
493        })
494    }
495}
496
497impl<T> Point<T> {
498    pub fn extract_resolve<R: Any>(&self) -> Option<(&Address, &R)> {
499        let ByAddressInner { address, resolve } =
500            self.origin.as_inner()?.downcast_ref::<ByAddressInner>()?;
501        let resolve = resolve.as_ref().any_ref().downcast_ref::<R>()?;
502        Some((address, resolve))
503    }
504}
505
506#[derive(ParseAsInline)]
507#[must_use]
508pub struct Point<T> {
509    hash: OptionalHash,
510    origin: Arc<dyn Fetch<T = T>>,
511}
512
513impl<T> PartialOrd for Point<T> {
514    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
515        Some(self.cmp(other))
516    }
517}
518
519impl<T> Ord for Point<T> {
520    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
521        self.hash().cmp(&other.hash())
522    }
523}
524
525impl<T> Eq for Point<T> {}
526
527impl<T> PartialEq for Point<T> {
528    fn eq(&self, other: &Self) -> bool {
529        self.hash() == other.hash()
530    }
531}
532
533impl<T> Clone for Point<T> {
534    fn clone(&self) -> Self {
535        Self {
536            hash: self.hash,
537            origin: self.origin.clone(),
538        }
539    }
540}
541
542impl<T> Point<T> {
543    pub fn from_origin(hash: Hash, origin: Arc<dyn Fetch<T = T>>) -> Self {
544        Self {
545            hash: hash.into(),
546            origin,
547        }
548    }
549
550    fn map_origin<U>(
551        self,
552        f: impl FnOnce(Arc<dyn Fetch<T = T>>) -> Arc<dyn Fetch<T = U>>,
553    ) -> Point<U> {
554        Point {
555            hash: self.hash,
556            origin: f(self.origin),
557        }
558    }
559}
560
561impl<T> Size for Point<T> {
562    const SIZE: usize = HASH_SIZE;
563    type Size = typenum::generic_const_mappings::U<HASH_SIZE>;
564}
565
566impl<T: Object> Point<T> {
567    pub fn from_address(address: Address, resolve: Arc<dyn Resolve>) -> Self {
568        Self::from_address_extra(address, resolve, ())
569    }
570}
571
572impl<T> Point<T> {
573    pub fn from_address_extra<Extra: 'static + Send + Sync + Clone>(
574        address: Address,
575        resolve: Arc<dyn Resolve>,
576        extra: Extra,
577    ) -> Self
578    where
579        T: Object<Extra>,
580    {
581        Self::from_origin(
582            address.hash,
583            Arc::new(ByAddress::from_inner(
584                ByAddressInner { address, resolve },
585                extra,
586            )),
587        )
588    }
589
590    pub fn with_resolve<Extra: 'static + Send + Sync + Clone>(
591        &self,
592        resolve: Arc<dyn Resolve>,
593        extra: Extra,
594    ) -> Self
595    where
596        T: Object<Extra>,
597    {
598        Self::from_address_extra(Address::from_hash(self.hash()), resolve, extra)
599    }
600}
601
602#[derive(Clone)]
603struct ByAddressInner {
604    address: Address,
605    resolve: Arc<dyn Resolve>,
606}
607
608impl FetchBytes for ByAddressInner {
609    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
610        self.resolve.resolve(self.address)
611    }
612
613    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
614        self.resolve.resolve_data(self.address)
615    }
616}
617
618struct ByAddress<T, Extra> {
619    inner: ByAddressInner,
620    extra: Extra,
621    _object: PhantomData<fn() -> T>,
622}
623
624impl<T, Extra: 'static + Clone> ByAddress<T, Extra> {
625    fn from_inner(inner: ByAddressInner, extra: Extra) -> Self {
626        Self {
627            inner,
628            extra,
629            _object: PhantomData,
630        }
631    }
632}
633
634impl<T, Extra: 'static> FetchBytes for ByAddress<T, Extra> {
635    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
636        self.inner.fetch_bytes()
637    }
638
639    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
640        self.inner.fetch_data()
641    }
642
643    fn as_inner(&self) -> Option<&dyn Any> {
644        Some(&self.inner)
645    }
646}
647
648impl<T: Object<Extra>, Extra: 'static + Send + Sync> Fetch for ByAddress<T, Extra> {
649    type T = T;
650
651    fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
652        Box::pin(async {
653            let (data, resolve) = self.fetch_bytes().await?;
654            let object = T::parse_slice_extra(&data, &resolve, &self.extra)?;
655            if self.inner.address.hash != object.full_hash() {
656                Err(Error::DataMismatch)
657            } else {
658                Ok((object, resolve))
659            }
660        })
661    }
662
663    fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
664        Box::pin(async {
665            let (data, resolve) = self.fetch_bytes().await?;
666            let object = T::parse_slice_extra(&data, &resolve, &self.extra)?;
667            if self.inner.address.hash != object.full_hash() {
668                Err(Error::DataMismatch)
669            } else {
670                Ok(object)
671            }
672        })
673    }
674}
675
676pub trait PointVisitor {
677    fn visit<T: Traversible>(&mut self, point: &Point<T>);
678}
679
680struct HashVisitor<F>(F);
681
682impl<F: FnMut(Hash)> PointVisitor for HashVisitor<F> {
683    fn visit<T: Traversible>(&mut self, point: &Point<T>) {
684        self.0(point.hash());
685    }
686}
687
688pub struct ReflessInput<'a> {
689    data: Option<&'a [u8]>,
690}
691
692pub struct Input<'a, Extra = ()> {
693    refless: ReflessInput<'a>,
694    resolve: &'a Arc<dyn Resolve>,
695    index: &'a Cell<usize>,
696    extra: &'a Extra,
697}
698
699impl<'a, Extra> Deref for Input<'a, Extra> {
700    type Target = ReflessInput<'a>;
701
702    fn deref(&self) -> &Self::Target {
703        &self.refless
704    }
705}
706
707impl<Extra> DerefMut for Input<'_, Extra> {
708    fn deref_mut(&mut self) -> &mut Self::Target {
709        &mut self.refless
710    }
711}
712
713impl<'a, Extra> Input<'a, Extra> {
714    pub fn replace_extra<E>(self, extra: &'a E) -> Input<'a, E> {
715        Input {
716            refless: self.refless,
717            resolve: self.resolve,
718            index: self.index,
719            extra,
720        }
721    }
722}
723
724impl<'a> ReflessInput<'a> {
725    fn data(&self) -> crate::Result<&'a [u8]> {
726        self.data.ok_or(Error::EndOfInput)
727    }
728
729    fn make_error<T>(&mut self, e: crate::Error) -> crate::Result<T> {
730        self.data = None;
731        Err(e)
732    }
733
734    fn end_of_input<T>(&mut self) -> crate::Result<T> {
735        self.make_error(Error::EndOfInput)
736    }
737}
738
739impl ParseInput for ReflessInput<'_> {
740    fn parse_chunk<'a, const N: usize>(&mut self) -> crate::Result<&'a [u8; N]>
741    where
742        Self: 'a,
743    {
744        match self.data()?.split_first_chunk() {
745            Some((chunk, data)) => {
746                self.data = Some(data);
747                Ok(chunk)
748            }
749            None => self.end_of_input(),
750        }
751    }
752
753    fn parse_n<'a>(&mut self, n: usize) -> crate::Result<&'a [u8]>
754    where
755        Self: 'a,
756    {
757        match self.data()?.split_at_checked(n) {
758            Some((chunk, data)) => {
759                self.data = Some(data);
760                Ok(chunk)
761            }
762            None => self.end_of_input(),
763        }
764    }
765
766    fn parse_ahead<T: Parse<Self>>(&mut self, n: usize) -> crate::Result<T> {
767        let input = ReflessInput {
768            data: Some(self.parse_n(n)?),
769        };
770        T::parse(input)
771    }
772
773    fn parse_compare<T: ParseInline<Self>>(&mut self, n: usize, c: &[u8]) -> Result<Option<T>> {
774        match self.data()?.split_at_checked(n) {
775            Some((chunk, data)) => {
776                if chunk == c {
777                    self.data = Some(data);
778                    Ok(None)
779                } else {
780                    self.parse_inline().map(Some)
781                }
782            }
783            None => self.end_of_input(),
784        }
785    }
786
787    fn parse_all<'a>(self) -> crate::Result<&'a [u8]>
788    where
789        Self: 'a,
790    {
791        self.data()
792    }
793
794    fn empty(self) -> crate::Result<()> {
795        if self.data()?.is_empty() {
796            Ok(())
797        } else {
798            Err(Error::ExtraInputLeft)
799        }
800    }
801
802    fn non_empty(self) -> crate::Result<Option<Self>> {
803        Ok(if self.data()?.is_empty() {
804            None
805        } else {
806            Some(self)
807        })
808    }
809}
810
811impl<Extra> ParseInput for Input<'_, Extra> {
812    fn parse_chunk<'a, const N: usize>(&mut self) -> crate::Result<&'a [u8; N]>
813    where
814        Self: 'a,
815    {
816        (**self).parse_chunk()
817    }
818
819    fn parse_n<'a>(&mut self, n: usize) -> crate::Result<&'a [u8]>
820    where
821        Self: 'a,
822    {
823        (**self).parse_n(n)
824    }
825
826    fn parse_ahead<T: Parse<Self>>(&mut self, n: usize) -> crate::Result<T> {
827        let input = Input {
828            refless: ReflessInput {
829                data: Some(self.parse_n(n)?),
830            },
831            resolve: self.resolve,
832            index: self.index,
833            extra: self.extra,
834        };
835        T::parse(input)
836    }
837
838    fn parse_compare<T: ParseInline<Self>>(&mut self, n: usize, c: &[u8]) -> Result<Option<T>> {
839        match self.data()?.split_at_checked(n) {
840            Some((chunk, data)) => {
841                if chunk == c {
842                    self.data = Some(data);
843                    Ok(None)
844                } else {
845                    self.parse_inline().map(Some)
846                }
847            }
848            None => self.end_of_input(),
849        }
850    }
851
852    fn parse_all<'a>(self) -> crate::Result<&'a [u8]>
853    where
854        Self: 'a,
855    {
856        self.refless.parse_all()
857    }
858
859    fn empty(self) -> crate::Result<()> {
860        self.refless.empty()
861    }
862
863    fn non_empty(mut self) -> crate::Result<Option<Self>> {
864        self.refless = match self.refless.non_empty()? {
865            Some(refless) => refless,
866            None => return Ok(None),
867        };
868        Ok(Some(self))
869    }
870}
871
872impl<'a, Extra: 'static + Clone> PointInput for Input<'a, Extra> {
873    type Extra = Extra;
874    type WithExtra<E: 'static + Clone> = Input<'a, E>;
875
876    fn next_index(&mut self) -> usize {
877        let index = self.index.get();
878        self.index.set(index + 1);
879        index
880    }
881
882    fn resolve_arc_ref(&self) -> &Arc<dyn Resolve> {
883        self.resolve
884    }
885
886    fn extra(&self) -> &Self::Extra {
887        self.extra
888    }
889
890    fn map_extra<E: 'static + Clone>(
891        self,
892        f: impl FnOnce(&Self::Extra) -> &E,
893    ) -> Self::WithExtra<E> {
894        let Self {
895            refless,
896            resolve,
897            index,
898            extra,
899        } = self;
900        Input {
901            refless,
902            resolve,
903            index,
904            extra: f(extra),
905        }
906    }
907}
908
909pub trait ToOutput {
910    fn to_output(&self, output: &mut dyn Output);
911
912    fn data_hash(&self) -> Hash {
913        let mut output = HashOutput::default();
914        self.to_output(&mut output);
915        output.hash()
916    }
917
918    fn slice_to_output(slice: &[Self], output: &mut dyn Output)
919    where
920        Self: Sized,
921    {
922        slice.iter_to_output(output);
923    }
924
925    fn output<T: Output + Default>(&self) -> T {
926        let mut output = T::default();
927        self.to_output(&mut output);
928        output
929    }
930
931    fn vec(&self) -> Vec<u8> {
932        self.output()
933    }
934}
935
936#[derive(Default)]
937struct CountVisitor {
938    count: usize,
939}
940
941impl PointVisitor for CountVisitor {
942    fn visit<T: Traversible>(&mut self, _: &Point<T>) {
943        self.count += 1;
944    }
945}
946
947pub trait Topological {
948    fn accept_points(&self, visitor: &mut impl PointVisitor) {
949        let _ = visitor;
950    }
951
952    fn topology_hash(&self) -> Hash {
953        let mut hasher = Sha256::new();
954        self.accept_points(&mut HashVisitor(|hash| hasher.update(hash)));
955        Hash::from_sha256(hasher.finalize().into())
956    }
957
958    fn point_count(&self) -> usize {
959        let mut visitor = CountVisitor::default();
960        self.accept_points(&mut visitor);
961        visitor.count
962    }
963
964    fn topology(&self) -> TopoVec {
965        let mut topology = TopoVec::with_capacity(self.point_count());
966        self.accept_points(&mut topology);
967        topology
968    }
969}
970
971pub trait Tagged {
972    const TAGS: Tags = Tags(&[], &[]);
973
974    const HASH: Hash =
975        const { Hash::from_sha256(Self::TAGS.const_hash(sha2_const::Sha256::new()).finalize()) };
976}
977
978pub trait ParseSlice: for<'a> Parse<Input<'a>> {
979    fn parse_slice(data: &[u8], resolve: &Arc<dyn Resolve>) -> crate::Result<Self> {
980        Self::parse_slice_extra(data, resolve, &())
981    }
982}
983
984impl<T: for<'a> Parse<Input<'a>>> ParseSlice for T {}
985
986pub trait ParseSliceExtra<Extra>: for<'a> Parse<Input<'a, Extra>> {
987    fn parse_slice_extra(
988        data: &[u8],
989        resolve: &Arc<dyn Resolve>,
990        extra: &Extra,
991    ) -> crate::Result<Self> {
992        let input = Input {
993            refless: ReflessInput { data: Some(data) },
994            resolve,
995            index: &Cell::new(0),
996            extra,
997        };
998        let object = Self::parse(input)?;
999        Ok(object)
1000    }
1001}
1002
1003impl<T: for<'a> Parse<Input<'a, Extra>>, Extra> ParseSliceExtra<Extra> for T {}
1004
1005#[derive(ToOutput)]
1006pub struct ObjectHashes {
1007    pub tags: Hash,
1008    pub topology: Hash,
1009    pub data: Hash,
1010}
1011
1012pub trait FullHash: ToOutput + Topological + Tagged {
1013    fn hashes(&self) -> ObjectHashes {
1014        ObjectHashes {
1015            tags: Self::HASH,
1016            topology: self.topology_hash(),
1017            data: self.data_hash(),
1018        }
1019    }
1020
1021    fn full_hash(&self) -> Hash {
1022        self.hashes().data_hash()
1023    }
1024}
1025
1026impl<T: ?Sized + ToOutput + Topological + Tagged> FullHash for T {}
1027
1028pub trait Traversible: 'static + Sized + Send + Sync + FullHash {
1029    fn to_resolve(&self) -> Arc<dyn Resolve> {
1030        Arc::new(ByTopology {
1031            topology: self.topology(),
1032        })
1033    }
1034
1035    fn point(self) -> Point<Self>
1036    where
1037        Self: Clone,
1038    {
1039        Point::from_object(self)
1040    }
1041}
1042
1043impl<T: 'static + Send + Sync + FullHash> Traversible for T {}
1044
1045pub trait Object<Extra: 'static = ()>: Traversible + for<'a> Parse<Input<'a, Extra>> {}
1046
1047pub struct Tags(pub &'static [&'static str], pub &'static [&'static Self]);
1048
1049impl Tags {
1050    const fn const_hash(&self, mut hasher: sha2_const::Sha256) -> sha2_const::Sha256 {
1051        {
1052            let mut i = 0;
1053            while i < self.0.len() {
1054                hasher = hasher.update(self.0[i].as_bytes());
1055                i += 1;
1056            }
1057        }
1058        {
1059            let mut i = 0;
1060            while i < self.1.len() {
1061                hasher = self.1[i].const_hash(hasher);
1062                i += 1;
1063            }
1064        }
1065        hasher
1066    }
1067}
1068
1069pub trait Inline<Extra: 'static = ()>:
1070    Object<Extra> + for<'a> ParseInline<Input<'a, Extra>>
1071{
1072}
1073
1074impl<T: Traversible> Topological for Point<T> {
1075    fn accept_points(&self, visitor: &mut impl PointVisitor) {
1076        visitor.visit(self);
1077    }
1078
1079    fn point_count(&self) -> usize {
1080        1
1081    }
1082}
1083
1084impl<T: Object<I::Extra>, I: PointInput<Extra: Send + Sync>> ParseInline<I> for Point<T> {
1085    fn parse_inline(input: &mut I) -> crate::Result<Self> {
1086        Ok(Self::from_address_extra(
1087            input.parse_inline()?,
1088            input.resolve(),
1089            input.extra().clone(),
1090        ))
1091    }
1092}
1093
1094impl<T: Tagged> Tagged for Point<T> {
1095    const TAGS: Tags = T::TAGS;
1096}
1097
1098impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Object<Extra> for Point<T> {}
1099
1100impl<T> ToOutput for Point<T> {
1101    fn to_output(&self, output: &mut dyn Output) {
1102        self.hash().to_output(output);
1103    }
1104}
1105
1106impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Inline<Extra> for Point<T> {}
1107
1108pub trait Topology: Send + Sync {
1109    fn len(&self) -> usize;
1110    fn get(&self, index: usize) -> Option<&Arc<dyn Singular>>;
1111
1112    fn is_empty(&self) -> bool {
1113        self.len() == 0
1114    }
1115}
1116
1117pub trait Singular: Send + Sync + FetchBytes {
1118    fn hash(&self) -> Hash;
1119}
1120
1121pub type TopoVec = Vec<Arc<dyn Singular>>;
1122
1123impl PointVisitor for TopoVec {
1124    fn visit<T: Traversible>(&mut self, point: &Point<T>) {
1125        self.push(Arc::new(point.clone()));
1126    }
1127}
1128
1129impl<T> FetchBytes for Point<T> {
1130    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
1131        self.origin.fetch_bytes()
1132    }
1133
1134    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
1135        self.origin.fetch_data()
1136    }
1137}
1138
1139impl<T> Singular for Point<T> {
1140    fn hash(&self) -> Hash {
1141        self.hash.unwrap()
1142    }
1143}
1144
1145impl Topology for TopoVec {
1146    fn len(&self) -> usize {
1147        self.len()
1148    }
1149
1150    fn get(&self, index: usize) -> Option<&Arc<dyn Singular>> {
1151        (**self).get(index)
1152    }
1153}
1154
1155pub trait ParseSliceRefless: for<'a> Parse<ReflessInput<'a>> {
1156    fn parse_slice_refless(data: &[u8]) -> crate::Result<Self> {
1157        let input = ReflessInput { data: Some(data) };
1158        let object = Self::parse(input)?;
1159        Ok(object)
1160    }
1161}
1162
1163impl<T: for<'a> Parse<ReflessInput<'a>>> ParseSliceRefless for T {}
1164
1165pub trait ReflessObject:
1166    'static + Sized + Send + Sync + ToOutput + Tagged + for<'a> Parse<ReflessInput<'a>>
1167{
1168}
1169
1170pub trait ReflessInline: ReflessObject + for<'a> ParseInline<ReflessInput<'a>> {
1171    fn parse_as_inline(mut input: ReflessInput) -> crate::Result<Self> {
1172        let object = Self::parse_inline(&mut input)?;
1173        input.empty()?;
1174        Ok(object)
1175    }
1176}
1177
1178pub trait Output {
1179    fn write(&mut self, data: &[u8]);
1180}
1181
1182impl Output for Vec<u8> {
1183    fn write(&mut self, data: &[u8]) {
1184        self.extend_from_slice(data);
1185    }
1186}
1187
1188impl Output for Vec<&'static str> {
1189    fn write(&mut self, data: &[u8]) {
1190        let _ = data;
1191    }
1192}
1193
1194#[derive(Default)]
1195struct HashOutput {
1196    hasher: Sha256,
1197    at: usize,
1198}
1199
1200impl Output for HashOutput {
1201    fn write(&mut self, data: &[u8]) {
1202        self.hasher.update(data);
1203        self.at += data.len();
1204    }
1205}
1206
1207impl HashOutput {
1208    fn hash(self) -> Hash {
1209        Hash::from_sha256(self.hasher.finalize().into())
1210    }
1211}
1212
1213pub struct PointMut<'a, T: FullHash> {
1214    hash: &'a mut OptionalHash,
1215    origin: &'a mut dyn Fetch<T = T>,
1216}
1217
1218impl<T: FullHash> Deref for PointMut<'_, T> {
1219    type Target = T;
1220
1221    fn deref(&self) -> &Self::Target {
1222        self.origin.get().unwrap()
1223    }
1224}
1225
1226impl<T: FullHash> DerefMut for PointMut<'_, T> {
1227    fn deref_mut(&mut self) -> &mut Self::Target {
1228        self.origin.get_mut().unwrap()
1229    }
1230}
1231
1232impl<T: FullHash> Drop for PointMut<'_, T> {
1233    fn drop(&mut self) {
1234        self.finalize();
1235    }
1236}
1237
1238impl<'a, T: FullHash> PointMut<'a, T> {
1239    fn finalize(&mut self) {
1240        self.origin.get_mut_finalize();
1241        *self.hash = self.full_hash().into();
1242    }
1243}
1244
1245impl<T: Traversible + Clone> Point<T> {
1246    pub fn from_object(object: T) -> Self {
1247        Self::from_origin(object.full_hash(), Arc::new(LocalOrigin { object }))
1248    }
1249
1250    fn yolo_mut(&mut self) -> bool {
1251        self.origin.get().is_some()
1252            && Arc::get_mut(&mut self.origin).is_some_and(|origin| origin.get_mut().is_some())
1253    }
1254
1255    async fn prepare_yolo_origin(&mut self) -> crate::Result<()> {
1256        if !self.yolo_mut() {
1257            let object = self.origin.fetch().await?;
1258            self.origin = Arc::new(LocalOrigin { object });
1259        }
1260        Ok(())
1261    }
1262
1263    pub async fn fetch_mut(&'_ mut self) -> crate::Result<PointMut<'_, T>> {
1264        self.prepare_yolo_origin().await?;
1265        let origin = Arc::get_mut(&mut self.origin).unwrap();
1266        assert!(origin.get_mut().is_some());
1267        self.hash.clear();
1268        Ok(PointMut {
1269            hash: &mut self.hash,
1270            origin,
1271        })
1272    }
1273
1274    pub async fn fetch_ref<Extra: 'static + Send + Sync + Clone>(&mut self) -> crate::Result<&T>
1275    where
1276        T: Object<Extra> + Clone,
1277    {
1278        self.prepare_yolo_origin().await?;
1279        Ok(self.origin.get().unwrap())
1280    }
1281}
1282
1283struct LocalOrigin<T> {
1284    object: T,
1285}
1286
1287impl<T> Deref for LocalOrigin<T> {
1288    type Target = T;
1289
1290    fn deref(&self) -> &Self::Target {
1291        &self.object
1292    }
1293}
1294
1295impl<T> DerefMut for LocalOrigin<T> {
1296    fn deref_mut(&mut self) -> &mut Self::Target {
1297        &mut self.object
1298    }
1299}
1300
1301impl<T: Traversible + Clone> Fetch for LocalOrigin<T> {
1302    type T = T;
1303
1304    fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
1305        Box::pin(ready(Ok((self.object.clone(), self.object.to_resolve()))))
1306    }
1307
1308    fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
1309        Box::pin(ready(Ok(self.object.clone())))
1310    }
1311
1312    fn get(&self) -> Option<&Self::T> {
1313        Some(self)
1314    }
1315
1316    fn get_mut(&mut self) -> Option<&mut Self::T> {
1317        Some(self)
1318    }
1319}
1320
1321impl<T: Traversible + Clone> FetchBytes for LocalOrigin<T> {
1322    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
1323        Box::pin(ready(Ok((self.object.output(), self.object.to_resolve()))))
1324    }
1325
1326    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
1327        Box::pin(ready(Ok(self.object.output())))
1328    }
1329}
1330
1331struct ByTopology {
1332    topology: TopoVec,
1333}
1334
1335impl ByTopology {
1336    fn try_resolve(&'_ self, address: Address) -> Result<FailFuture<'_, ByteNode>> {
1337        let point = self
1338            .topology
1339            .get(address.index)
1340            .ok_or(Error::AddressOutOfBounds)?;
1341        if point.hash() != address.hash {
1342            Err(Error::ResolutionMismatch)
1343        } else {
1344            Ok(point.fetch_bytes())
1345        }
1346    }
1347
1348    fn try_resolve_data(&'_ self, address: Address) -> Result<FailFuture<'_, Vec<u8>>> {
1349        let point = self
1350            .topology
1351            .get(address.index)
1352            .ok_or(Error::AddressOutOfBounds)?;
1353        if point.hash() != address.hash {
1354            Err(Error::ResolutionMismatch)
1355        } else {
1356            Ok(point.fetch_data())
1357        }
1358    }
1359}
1360
1361impl Resolve for ByTopology {
1362    fn resolve(&'_ self, address: Address) -> FailFuture<'_, ByteNode> {
1363        self.try_resolve(address)
1364            .map_err(Err)
1365            .map_err(ready)
1366            .map_err(Box::pin)
1367            .unwrap_or_else(|x| x)
1368    }
1369
1370    fn resolve_data(&'_ self, address: Address) -> FailFuture<'_, Vec<u8>> {
1371        self.try_resolve_data(address)
1372            .map_err(Err)
1373            .map_err(ready)
1374            .map_err(Box::pin)
1375            .unwrap_or_else(|x| x)
1376    }
1377
1378    fn name(&self) -> &str {
1379        "by topology"
1380    }
1381}
1382
1383impl<T: FullHash> Fetch for Point<T> {
1384    type T = T;
1385
1386    fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
1387        self.origin.fetch_full()
1388    }
1389
1390    fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
1391        self.origin.fetch()
1392    }
1393
1394    fn get(&self) -> Option<&Self::T> {
1395        self.origin.get()
1396    }
1397
1398    fn get_mut(&mut self) -> Option<&mut Self::T> {
1399        self.hash.clear();
1400        Arc::get_mut(&mut self.origin)?.get_mut()
1401    }
1402
1403    fn get_mut_finalize(&mut self) {
1404        let origin = Arc::get_mut(&mut self.origin).unwrap();
1405        origin.get_mut_finalize();
1406        self.hash = origin.get().unwrap().full_hash().into();
1407    }
1408}
1409
1410pub trait Size {
1411    const SIZE: usize = <Self::Size as Unsigned>::USIZE;
1412    type Size: Unsigned;
1413}
1414
1415pub trait SizeExt: Size<Size: ArrayLength> + ToOutput {
1416    fn to_array(&self) -> GenericArray<u8, Self::Size> {
1417        let mut array = GenericArray::default();
1418        let mut output = ArrayOutput {
1419            data: &mut array,
1420            offset: 0,
1421        };
1422        self.to_output(&mut output);
1423        output.finalize();
1424        array
1425    }
1426}
1427
1428impl<T: Size<Size: ArrayLength> + ToOutput> SizeExt for T {}
1429
1430struct ArrayOutput<'a> {
1431    data: &'a mut [u8],
1432    offset: usize,
1433}
1434
1435impl ArrayOutput<'_> {
1436    fn finalize(self) {
1437        assert_eq!(self.offset, self.data.len());
1438    }
1439}
1440
1441impl Output for ArrayOutput<'_> {
1442    fn write(&mut self, data: &[u8]) {
1443        self.data[self.offset..][..data.len()].copy_from_slice(data);
1444        self.offset += data.len();
1445    }
1446}
1447
1448trait RainbowIterator: Sized + IntoIterator {
1449    fn iter_to_output(self, output: &mut dyn Output)
1450    where
1451        Self::Item: ToOutput,
1452    {
1453        self.into_iter().for_each(|item| item.to_output(output));
1454    }
1455
1456    fn iter_accept_points(self, visitor: &mut impl PointVisitor)
1457    where
1458        Self::Item: Topological,
1459    {
1460        self.into_iter()
1461            .for_each(|item| item.accept_points(visitor));
1462    }
1463}
1464
1465pub trait ParseInput: Sized {
1466    fn parse_chunk<'a, const N: usize>(&mut self) -> crate::Result<&'a [u8; N]>
1467    where
1468        Self: 'a;
1469    fn parse_n<'a>(&mut self, n: usize) -> crate::Result<&'a [u8]>
1470    where
1471        Self: 'a;
1472    fn parse_ahead<T: Parse<Self>>(&mut self, n: usize) -> crate::Result<T>;
1473    fn parse_compare<T: ParseInline<Self>>(&mut self, n: usize, c: &[u8]) -> Result<Option<T>>;
1474    fn parse_all<'a>(self) -> crate::Result<&'a [u8]>
1475    where
1476        Self: 'a;
1477    fn empty(self) -> crate::Result<()>;
1478    fn non_empty(self) -> crate::Result<Option<Self>>;
1479
1480    fn consume(self, f: impl FnMut(&mut Self) -> crate::Result<()>) -> crate::Result<()> {
1481        self.collect(f)
1482    }
1483
1484    fn parse_collect<T: ParseInline<Self>, B: FromIterator<T>>(self) -> crate::Result<B> {
1485        self.collect(|input| input.parse_inline())
1486    }
1487
1488    fn collect<T, B: FromIterator<T>>(
1489        self,
1490        f: impl FnMut(&mut Self) -> crate::Result<T>,
1491    ) -> crate::Result<B> {
1492        self.iter(f).collect()
1493    }
1494
1495    fn iter<T>(
1496        self,
1497        mut f: impl FnMut(&mut Self) -> crate::Result<T>,
1498    ) -> impl Iterator<Item = crate::Result<T>> {
1499        let mut state = Some(self);
1500        std::iter::from_fn(move || {
1501            let mut input = match state.take()?.non_empty() {
1502                Ok(input) => input,
1503                Err(e) => return Some(Err(e)),
1504            }?;
1505            let item = f(&mut input);
1506            state = Some(input);
1507            Some(item)
1508        })
1509    }
1510
1511    fn parse_inline<T: ParseInline<Self>>(&mut self) -> crate::Result<T> {
1512        T::parse_inline(self)
1513    }
1514
1515    fn parse<T: Parse<Self>>(self) -> crate::Result<T> {
1516        T::parse(self)
1517    }
1518
1519    fn parse_vec<T: ParseInline<Self>>(self) -> crate::Result<Vec<T>> {
1520        T::parse_vec(self)
1521    }
1522}
1523
1524pub trait PointInput: ParseInput {
1525    type Extra: 'static + Clone;
1526    type WithExtra<E: 'static + Clone>: PointInput<Extra = E, WithExtra<Self::Extra> = Self>;
1527    fn next_index(&mut self) -> usize;
1528    fn resolve_arc_ref(&self) -> &Arc<dyn Resolve>;
1529    fn resolve(&self) -> Arc<dyn Resolve> {
1530        self.resolve_arc_ref().clone()
1531    }
1532    fn resolve_ref(&self) -> &dyn Resolve {
1533        self.resolve_arc_ref().as_ref()
1534    }
1535    fn extension<T: Any>(&self) -> crate::Result<&T> {
1536        self.resolve_ref()
1537            .extension(TypeId::of::<T>())?
1538            .downcast_ref()
1539            .ok_or(Error::ExtensionType)
1540    }
1541    fn extra(&self) -> &Self::Extra;
1542    fn map_extra<E: 'static + Clone>(
1543        self,
1544        f: impl FnOnce(&Self::Extra) -> &E,
1545    ) -> Self::WithExtra<E>;
1546}
1547
1548impl<T: Sized + IntoIterator> RainbowIterator for T {}
1549
1550pub trait Parse<I: ParseInput>: Sized {
1551    fn parse(input: I) -> crate::Result<Self>;
1552}
1553
1554pub trait ParseInline<I: ParseInput>: Parse<I> {
1555    fn parse_inline(input: &mut I) -> crate::Result<Self>;
1556    fn parse_as_inline(mut input: I) -> crate::Result<Self> {
1557        let object = Self::parse_inline(&mut input)?;
1558        input.empty()?;
1559        Ok(object)
1560    }
1561    fn parse_vec(input: I) -> crate::Result<Vec<Self>> {
1562        input.parse_collect()
1563    }
1564}
1565
1566/// Implemented if both types have the exact same layout.
1567/// This implies having the same [`MaybeHasNiche::MnArray`].
1568///
1569/// This is represented as two-way conversion for two reasons:
1570/// - to highlight that the conversion is actual equivalence
1571/// - to increase flexibility (mostly to go around the orphan rule)
1572pub trait Equivalent<T>: Sized {
1573    /// Inverse of [`Equivalent::from_equivalent`].
1574    fn into_equivalent(self) -> T;
1575    /// Inverse of [`Equivalent::into_equivalent`].
1576    fn from_equivalent(object: T) -> Self;
1577}
1578
1579/// This implementation is the main goal of [`Equivalent`]: we assume transmuting the pointer is
1580/// safe.
1581impl<U: 'static + Equivalent<T>, T: 'static> Equivalent<Point<T>> for Point<U> {
1582    fn into_equivalent(self) -> Point<T> {
1583        self.map_origin(|origin| {
1584            Arc::new(MapEquivalent {
1585                origin,
1586                map: U::into_equivalent,
1587            })
1588        })
1589    }
1590
1591    fn from_equivalent(point: Point<T>) -> Self {
1592        point.map_origin(|origin| {
1593            Arc::new(MapEquivalent {
1594                origin,
1595                map: U::from_equivalent,
1596            })
1597        })
1598    }
1599}
1600
1601struct MapEquivalent<T, F> {
1602    origin: Arc<dyn Fetch<T = T>>,
1603    map: F,
1604}
1605
1606impl<T, F> FetchBytes for MapEquivalent<T, F> {
1607    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
1608        self.origin.fetch_bytes()
1609    }
1610
1611    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
1612        self.origin.fetch_data()
1613    }
1614}
1615
1616trait Map1<T>: Fn(T) -> Self::U {
1617    type U;
1618}
1619
1620impl<T, U, F: Fn(T) -> U> Map1<T> for F {
1621    type U = U;
1622}
1623
1624impl<T, F: 'static + Send + Sync + Map1<T>> Fetch for MapEquivalent<T, F> {
1625    type T = F::U;
1626
1627    fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
1628        Box::pin(self.origin.fetch_full().map_ok(|(x, r)| ((self.map)(x), r)))
1629    }
1630
1631    fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
1632        Box::pin(self.origin.fetch().map_ok(&self.map))
1633    }
1634}
1635
1636impl<T: 'static + ToOutput> Point<T> {
1637    pub fn map<U>(self, map: impl 'static + Send + Sync + Fn(T) -> U) -> Point<U> {
1638        self.map_origin(|origin| Arc::new(Map { origin, map }))
1639    }
1640}
1641
1642struct Map<T, F> {
1643    origin: Arc<dyn Fetch<T = T>>,
1644    map: F,
1645}
1646
1647impl<T: ToOutput, F> FetchBytes for Map<T, F> {
1648    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
1649        Box::pin(self.origin.fetch_full().map_ok(|(x, r)| (x.output(), r)))
1650    }
1651
1652    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
1653        Box::pin(self.origin.fetch().map_ok(|x| x.output()))
1654    }
1655}
1656
1657impl<T: ToOutput, F: 'static + Send + Sync + Map1<T>> Fetch for Map<T, F> {
1658    type T = F::U;
1659
1660    fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
1661        Box::pin(self.origin.fetch_full().map_ok(|(x, r)| ((self.map)(x), r)))
1662    }
1663
1664    fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
1665        Box::pin(self.origin.fetch().map_ok(&self.map))
1666    }
1667}
1668
1669impl<T> MaybeHasNiche for Point<T> {
1670    type MnArray = <Hash as MaybeHasNiche>::MnArray;
1671}
1672
1673impl<T: FullHash + Default> Point<T> {
1674    pub fn is_default(&self) -> bool {
1675        self.hash() == T::default().full_hash()
1676    }
1677}
1678
1679impl<T: Default + Traversible + Clone> Default for Point<T> {
1680    fn default() -> Self {
1681        T::default().point()
1682    }
1683}
1684
1685#[test]
1686fn options() {
1687    type T0 = ();
1688    type T1 = Option<T0>;
1689    type T2 = Option<T1>;
1690    type T3 = Option<T2>;
1691    type T4 = Option<T3>;
1692    type T5 = Option<T4>;
1693    assert_eq!(T0::SIZE, 0);
1694    assert_eq!(T1::SIZE, 1);
1695    assert_eq!(T2::SIZE, 1);
1696    assert_eq!(T3::SIZE, 1);
1697    assert_eq!(T4::SIZE, 1);
1698    assert_eq!(T5::SIZE, 1);
1699    assert_eq!(Some(Some(Some(()))).vec(), [0]);
1700    assert_eq!(Some(Some(None::<()>)).vec(), [1]);
1701    assert_eq!(Some(None::<Option<()>>).vec(), [2]);
1702    assert_eq!(None::<Option<Option<()>>>.vec(), [3]);
1703
1704    assert_eq!(false.vec(), [0]);
1705    assert_eq!(true.vec(), [1]);
1706    assert_eq!(Some(false).vec(), [0]);
1707    assert_eq!(Some(true).vec(), [1]);
1708    assert_eq!(None::<bool>.vec(), [2]);
1709    assert_eq!(Some(Some(false)).vec(), [0]);
1710    assert_eq!(Some(Some(true)).vec(), [1]);
1711    assert_eq!(Some(None::<bool>).vec(), [2]);
1712    assert_eq!(None::<Option<bool>>.vec(), [3]);
1713    assert_eq!(Some(Some(Some(false))).vec(), [0]);
1714    assert_eq!(Some(Some(Some(true))).vec(), [1]);
1715    assert_eq!(Some(Some(None::<bool>)).vec(), [2]);
1716    assert_eq!(Some(None::<Option<bool>>).vec(), [3]);
1717    assert_eq!(None::<Option<Option<bool>>>.vec(), [4]);
1718    assert_eq!(Option::<Point<()>>::SIZE, HASH_SIZE);
1719    assert_eq!(Some(()).vec(), [0]);
1720    assert_eq!(Some(((), ())).vec(), [0]);
1721    assert_eq!(Some(((), true)).vec(), [1]);
1722    assert_eq!(Some((true, true)).vec(), [1, 1]);
1723    assert_eq!(Some((Some(true), true)).vec(), [1, 1]);
1724    assert_eq!(Some((None::<bool>, true)).vec(), [2, 1]);
1725    assert_eq!(Some((true, None::<bool>)).vec(), [1, 2]);
1726    assert_eq!(None::<(Option<bool>, bool)>.vec(), [3, 2]);
1727    assert_eq!(None::<(bool, Option<bool>)>.vec(), [2, 3]);
1728    assert_eq!(Some(Some((Some(true), Some(true)))).vec(), [1, 1],);
1729    assert_eq!(Option::<Point<()>>::SIZE, HASH_SIZE);
1730    assert_eq!(Option::<Option<Point<()>>>::SIZE, HASH_SIZE);
1731    assert_eq!(Option::<Option<Option<Point<()>>>>::SIZE, HASH_SIZE);
1732}