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