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