object_rainbow/
lib.rs

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