Skip to main content

object_rainbow/
lib.rs

1#![forbid(unsafe_code)]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![cfg_attr(docsrs, doc(cfg_hide(doc)))]
4
5extern crate self as object_rainbow;
6
7use std::{
8    any::Any,
9    borrow::Cow,
10    cell::Cell,
11    cmp::Ordering,
12    convert::Infallible,
13    future::ready,
14    marker::PhantomData,
15    ops::{Add, Deref, DerefMut, Sub},
16    pin::Pin,
17    sync::Arc,
18};
19
20#[doc(hidden)]
21pub use anyhow::anyhow;
22use futures_concurrency::future::TryJoin;
23use generic_array::{ArrayLength, GenericArray, functional::FunctionalSequence, sequence::Split};
24pub use object_rainbow_derive::{
25    CanonicalExtra, Enum, InlineOutput, ListHashes, MaybeHasNiche, Parse, ParseAsInline,
26    ParseInline, Size, Tagged, ToCanonicalExtra, ToOutput, Topological, derive_for_wrapped, pod,
27};
28use sha2::{Digest, Sha256};
29#[doc(hidden)]
30pub use typenum;
31use typenum::Unsigned;
32
33#[doc(hidden)]
34pub use self::niche::{MaybeNiche, MnArray, NicheFoldOrArray, NicheOr};
35pub use self::{
36    enumkind::Enum,
37    error::{Error, Result},
38    hash::{Hash, OptionalHash},
39    monostate::Monostate,
40    niche::{
41        AutoEnumNiche, AutoNiche, HackNiche, MaybeHasNiche, MinNiche, Niche, NicheForUnsized,
42        NoNiche, OneNiche, SomeNiche, ZeroNiche, ZeroNoNiche,
43    },
44    ordering::{ByteOrd, OrderedByBytes, SignificantLength},
45};
46
47pub mod addressed;
48pub mod ascii;
49mod assert_impl;
50pub mod decr_byte_niche;
51pub mod default_chain;
52pub mod default_terminated;
53pub mod enumkind;
54mod error;
55pub mod extra_none_terminated;
56pub mod extra_option;
57pub mod extras;
58pub mod ff;
59pub mod fn_fetch;
60pub mod hash;
61pub mod hashed;
62mod impls;
63pub mod incr_byte_niche;
64pub mod inline_extra;
65pub mod length_prefixed;
66pub mod local_fetch;
67pub mod map_extra;
68mod monostate;
69pub mod monostate_headers;
70pub mod nested_mut;
71mod niche;
72pub mod niche_cut;
73pub mod none_terminated;
74pub mod numeric;
75pub mod object_marker;
76mod ordering;
77pub mod parse_extra;
78pub mod partial_byte_tag;
79pub mod refless;
80pub mod runtime_array;
81pub mod sequence;
82pub mod tuple_extra;
83pub mod tuple_of_arrays;
84pub mod u63;
85pub mod with_repr;
86pub mod zero_terminated;
87
88/// SHA-256 hash size in bytes.
89pub const HASH_SIZE: usize = sha2_const::Sha256::DIGEST_SIZE;
90
91/// Address within a [`PointInput`].
92///
93/// This was introduced:
94/// - to avoid using a [`Hash`]-only map
95/// - to differentiate between separate [`Hash`]es within a context
96///
97/// While [`Address`] implements a bunch of `trait`s from the object hierarchy, it's not a member of
98/// it: [`Address`]es are supposed to be used with [`Resolve`]s. Thus, it notably doesn't implement
99/// [`Topological`].
100#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ParseAsInline)]
101pub struct Address {
102    /// Monotonically incremented index. This is not present at all in the actual format.
103    pub index: usize,
104    /// Only this part is part of the parsed/generated input.
105    pub hash: Hash,
106}
107
108impl Address {
109    /// Construct an address which is invalid within parsing context, but can be used in map-based
110    /// [`Resolve`]s.
111    pub fn from_hash(hash: Hash) -> Self {
112        Self {
113            index: usize::MAX,
114            hash,
115        }
116    }
117}
118
119/// The only valid connection between an [`Address`] and serialisation is in its [`Hash`].
120impl ToOutput for Address {
121    fn to_output(&self, output: &mut (impl ?Sized + Output)) {
122        self.hash.to_output(output);
123    }
124}
125
126impl InlineOutput for Address {}
127impl Tagged for Address {}
128
129impl ListHashes for Address {
130    fn list_hashes(&self, f: &mut (impl ?Sized + FnMut(Hash))) {
131        f(self.hash);
132    }
133}
134
135/// This is where [`PointInput::next_index`] is used.
136impl<I: PointInput> ParseInline<I> for Address {
137    fn parse_inline(input: &mut I) -> crate::Result<Self> {
138        Ok(Self {
139            index: input.next_index(),
140            hash: input.parse_inline()?,
141        })
142    }
143}
144
145impl Size for Address {
146    type Size = <Hash as Size>::Size;
147    const SIZE: usize = <Hash as Size>::SIZE;
148}
149
150impl MaybeHasNiche for Address {
151    type MnArray = <Hash as MaybeHasNiche>::MnArray;
152}
153
154/// Fallible future type yielding either `T` or [`Error`].
155pub type FailFuture<'a, T> = Pin<Box<dyn 'a + Send + Future<Output = Result<T>>>>;
156
157/// Returned by [`Resolve`] and [`FetchBytes`]. Represents traversal through the object graph.
158pub type ByteNode = (Vec<u8>, Arc<dyn Resolve>);
159
160/// Trait for contextually using [`Any`]. Can itself be implemented for non-`'static` and `?Sized`
161/// types, and is `dyn`-compatible.
162pub trait AsAny {
163    /// Get a shared RTTI reference.
164    fn any_ref(&self) -> &dyn Any
165    where
166        Self: 'static;
167    /// Get an exclusive RTTI reference.
168    fn any_mut(&mut self) -> &mut dyn Any
169    where
170        Self: 'static;
171    /// Get an RTTI [`Box`].
172    fn any_box(self: Box<Self>) -> Box<dyn Any>
173    where
174        Self: 'static;
175    /// Get an RTTI [`Arc`].
176    fn any_arc(self: Arc<Self>) -> Arc<dyn Any>
177    where
178        Self: 'static;
179    /// Get an RTTI [`Arc`] which is also [`Send`].
180    fn any_arc_sync(self: Arc<Self>) -> Arc<dyn Send + Sync + Any>
181    where
182        Self: 'static + Send + Sync;
183}
184
185impl<T> AsAny for T {
186    fn any_ref(&self) -> &dyn Any
187    where
188        Self: 'static,
189    {
190        self
191    }
192
193    fn any_mut(&mut self) -> &mut dyn Any
194    where
195        Self: 'static,
196    {
197        self
198    }
199
200    fn any_box(self: Box<Self>) -> Box<dyn Any>
201    where
202        Self: 'static,
203    {
204        self
205    }
206
207    fn any_arc(self: Arc<Self>) -> Arc<dyn Any>
208    where
209        Self: 'static,
210    {
211        self
212    }
213
214    fn any_arc_sync(self: Arc<Self>) -> Arc<dyn Send + Sync + Any>
215    where
216        Self: 'static + Send + Sync,
217    {
218        self
219    }
220}
221
222/// Something that can resolve [`Address`]es to [`ByteNode`]s.
223pub trait Resolve: Send + Sync + AsAny {
224    /// Resolve the address. For an [`Object`], this is what gets used as [`PointInput`].
225    ///
226    /// `this` points to same thing as `self`. Provided for ease of cloning [`Hash`]-based
227    /// [`Resolve`]s.
228    fn resolve<'a>(
229        &'a self,
230        address: Address,
231        this: &'a Arc<dyn Resolve>,
232    ) -> FailFuture<'a, ByteNode>;
233    /// Resolve data only (without a nested [`Resolve`]).
234    fn resolve_data(&'_ self, address: Address) -> FailFuture<'_, Vec<u8>>;
235    /// Attempt resolving assuming something is local. Returns [`None`] when it's not known to be
236    /// local.
237    fn try_resolve_local(
238        &self,
239        address: Address,
240        this: &Arc<dyn Resolve>,
241    ) -> Result<Option<ByteNode>> {
242        let _ = address;
243        let _ = this;
244        Ok(None)
245    }
246    /// Topology hash of the underyling sequence if this resolver is index-based.
247    fn topology_hash(&self) -> Option<Hash> {
248        None
249    }
250    /// Attempt unwrapping a [`TopoVec`]. Generally shouldn't be implemented.
251    fn into_topovec(self: Arc<Self>) -> Option<TopoVec> {
252        None
253    }
254}
255
256/// No-op matching the [`ParseInline`].
257impl ToOutput for dyn '_ + Resolve {
258    fn to_output(&self, _: &mut (impl ?Sized + Output)) {}
259}
260
261impl InlineOutput for dyn '_ + Resolve {}
262impl Tagged for dyn '_ + Resolve {}
263impl ListHashes for dyn '_ + Resolve {}
264
265impl Size for dyn '_ + Resolve {
266    type Size = typenum::U0;
267    const SIZE: usize = 0;
268}
269
270impl MaybeHasNiche for dyn '_ + Resolve {
271    type MnArray = NoNiche<ZeroNoNiche<<Self as Size>::Size>>;
272}
273
274impl<I: PointInput> Parse<I> for Arc<dyn '_ + Resolve> {
275    fn parse(input: I) -> crate::Result<Self> {
276        Self::parse_as_inline(input)
277    }
278}
279
280/// Just clone the [`Resolve`] from [`PointInput`].
281impl<I: PointInput> ParseInline<I> for Arc<dyn '_ + Resolve> {
282    fn parse_inline(input: &mut I) -> crate::Result<Self> {
283        Ok(input.resolve())
284    }
285}
286
287/// Main machinery responsible for turning content-addressed structures into something we can
288/// actually traverse.
289pub trait FetchBytes: AsAny {
290    /// Central method for traversal of [`Hash`]-based pointers. Returns byte data and [`Resolve`]
291    /// for use in [`Parse`].
292    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode>;
293    /// Only fetch data.
294    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>>;
295    /// Attempt to fetch a node as if it's local. Returns [`None`] if it's not known to be local.
296    fn fetch_bytes_local(&self) -> Result<Option<ByteNode>> {
297        Ok(None)
298    }
299    /// Returns data if it's local and trivially/infallibly available.
300    fn fetch_data_local(&self) -> Option<Vec<u8>> {
301        None
302    }
303    /// Reduce to some known grounded value, preferably one implementing [`FetchBytes`]. Typically,
304    /// this is [`addressed::AddressedBytes`].
305    fn as_inner(&self) -> Option<&dyn Any> {
306        None
307    }
308    /// Generalisation of [`FetchBytes::as_inner`] where we're only interested in the [`Resolve`]
309    /// component.
310    fn as_resolve(&self) -> Option<&Arc<dyn Resolve>> {
311        None
312    }
313    /// Attempt unwrapping a [`Resolve`]. Should be implemented when possible, as it's use for some
314    /// anti-stack-overflow machinery.
315    fn try_unwrap_resolve(self: Arc<Self>) -> Option<Arc<dyn Resolve>> {
316        None
317    }
318}
319
320/// Application-facing traversal.
321pub trait Fetch: Send + Sync + FetchBytes {
322    /// Fetched object.
323    type T;
324    /// Main traversal method.
325    fn fetch(&'_ self) -> FailFuture<'_, Self::T>;
326    /// Attempt to fetch the object locally.
327    ///
328    /// Generally this is either [`Fetch::get`]+[`Clone::clone`] or
329    /// [`FetchBytes::fetch_bytes_local`]+[`Parse::parse`].
330    fn try_fetch_local(&self) -> Result<Option<Self::T>> {
331        Ok(None)
332    }
333    /// Fetch locally if possible. Typically this is just [`Fetch::get`]+[`Clone::clone`].
334    fn fetch_local(&self) -> Option<Self::T> {
335        None
336    }
337    /// Get a reference to a locally stored object.
338    fn get(&self) -> Option<&Self::T> {
339        None
340    }
341    /// Get a mutable reference to a locally stored object.
342    ///
343    /// [`Fetch::get_mut_finalize`] must be called to restore the state even if no mutations were
344    /// made.
345    fn get_mut(&mut self) -> Option<&mut Self::T> {
346        None
347    }
348    /// Restore the inner state after mutations completed (for example, [`Hash`] of what's stored).
349    fn get_mut_finalize(&mut self) {}
350    /// Attempt unwrapping the object stored locally.
351    fn try_unwrap(self: Arc<Self>) -> Option<Self::T> {
352        None
353    }
354    /// Convenience method to force a conversion to a trait object.
355    fn into_dyn_fetch<'a>(self) -> Arc<dyn 'a + Fetch<T = Self::T>>
356    where
357        Self: 'a + Sized,
358    {
359        Arc::new(self)
360    }
361}
362
363/// Even though we refer to something, we don't know [`Hash`] for it. To match correctness, we don't
364/// `impl`ement [`Parse`]/[`ParseInline`].
365impl<T> ToOutput for dyn '_ + Fetch<T = T> {
366    fn to_output(&self, _: &mut (impl ?Sized + Output)) {}
367}
368
369impl<T> InlineOutput for dyn '_ + Fetch<T = T> {}
370
371impl<T: Tagged> Tagged for dyn '_ + Fetch<T = T> {
372    const TAGS: Tags = T::TAGS;
373    const HASH: Hash = T::HASH;
374}
375
376impl<T> PartialEq for dyn '_ + Fetch<T = T> {
377    fn eq(&self, _: &Self) -> bool {
378        true
379    }
380}
381
382impl<T> Eq for dyn '_ + Fetch<T = T> {}
383
384impl<T> PartialOrd for dyn '_ + Fetch<T = T> {
385    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
386        Some(self.cmp(other))
387    }
388}
389
390impl<T> Ord for dyn '_ + Fetch<T = T> {
391    fn cmp(&self, _: &Self) -> Ordering {
392        Ordering::Equal
393    }
394}
395
396impl<T> std::hash::Hash for dyn '_ + Fetch<T = T> {
397    fn hash<H: std::hash::Hasher>(&self, _: &mut H) {}
398}
399
400impl<T> ByteOrd for dyn '_ + Fetch<T = T> {
401    fn bytes_cmp(&self, _: &Self) -> Ordering {
402        Ordering::Equal
403    }
404}
405
406/// Used in [`Topological::traverse`].
407pub trait PointVisitor {
408    /// Visit one [`SingularFetch`] of an object. Points are provided in a fixed known order (mostly
409    /// means order of parsing).
410    fn visit(&mut self, point: &(impl 'static + SingularFetch<T: Traversible> + Clone));
411}
412
413struct ReflessData<'d> {
414    slice: &'d [u8],
415    prefix: Vec<Vec<u8>>,
416}
417
418impl<'a> ReflessData<'a> {
419    fn split_at_checked(&self, mut n: usize) -> Option<(Self, Self)> {
420        let mut prefix_l = Vec::new();
421        let mut prefix_r = self.prefix.clone();
422        while n > 0
423            && let Some(front) = prefix_r.last_mut()
424        {
425            if n < front.len() {
426                prefix_l.push(Vec::from(&front[..n]));
427                front.drain(..n);
428                n = 0;
429            } else {
430                n -= front.len();
431                prefix_l.push(prefix_r.pop().expect("last element is known to exist"));
432            }
433        }
434        prefix_l.reverse();
435        self.slice.split_at_checked(n).map(|(slice_l, slice_r)| {
436            (
437                Self {
438                    slice: slice_l,
439                    prefix: prefix_l,
440                },
441                Self {
442                    slice: slice_r,
443                    prefix: prefix_r,
444                },
445            )
446        })
447    }
448
449    fn len(&self) -> usize {
450        self.slice.len() + self.prefix.iter().map(|v| v.len()).sum::<usize>()
451    }
452
453    fn is_empty(&self) -> bool {
454        self.slice.is_empty() && self.prefix.iter().all(|v| v.is_empty())
455    }
456
457    fn starts_with(&self, mut prefix: &[u8]) -> bool {
458        for chunk in self.prefix.iter().rev() {
459            if chunk.starts_with(prefix) {
460                return true;
461            }
462            if let Some(rest) = prefix.strip_prefix(&**chunk) {
463                prefix = rest;
464            } else {
465                return false;
466            }
467        }
468        self.slice.starts_with(prefix)
469    }
470
471    fn cow(&self) -> Cow<'a, [u8]> {
472        if self.prefix.iter().all(|v| v.is_empty()) {
473            Cow::from(self.slice)
474        } else {
475            let mut vec = Vec::with_capacity(self.len());
476            for v in self.prefix.iter().rev() {
477                vec.extend_from_slice(v);
478            }
479            vec.extend_from_slice(self.slice);
480            Cow::from(vec)
481        }
482    }
483
484    fn iter(&self) -> impl Iterator<Item = &u8> {
485        self.prefix.iter().rev().flatten().chain(self.slice)
486    }
487}
488
489/// Simplest provided implementation of [`ParseInput`].
490///
491/// Generally, you shouldn't be referring to this (see [`ReflessObject`], [`ReflessInline`]).
492pub struct ReflessInput<'d> {
493    data: Option<ReflessData<'d>>,
494}
495
496/// Canonical implementation of [`PointInput`].
497///
498/// Generally, you shouldn't be referring to this (see [`Object`], [`Inline`] and [`ExtraFor`]).
499pub struct Input<'d, Extra: Clone = ()> {
500    refless: ReflessInput<'d>,
501    resolve: Cow<'d, Arc<dyn Resolve>>,
502    index: &'d Cell<usize>,
503    extra: Cow<'d, Extra>,
504}
505
506impl<'a, Extra: Clone> Deref for Input<'a, Extra> {
507    type Target = ReflessInput<'a>;
508
509    fn deref(&self) -> &Self::Target {
510        &self.refless
511    }
512}
513
514impl<Extra: Clone> DerefMut for Input<'_, Extra> {
515    fn deref_mut(&mut self) -> &mut Self::Target {
516        &mut self.refless
517    }
518}
519
520impl<'a> ReflessInput<'a> {
521    fn data(&self) -> crate::Result<&ReflessData<'a>> {
522        self.data.as_ref().ok_or(Error::EndOfInput)
523    }
524
525    fn data_mut(&mut self) -> crate::Result<&mut ReflessData<'a>> {
526        self.data.as_mut().ok_or(Error::EndOfInput)
527    }
528
529    fn make_error<T>(&mut self, e: crate::Error) -> crate::Result<T> {
530        self.data = None;
531        Err(e)
532    }
533
534    fn end_of_input<T>(&mut self) -> crate::Result<T> {
535        self.make_error(Error::EndOfInput)
536    }
537}
538
539impl<'d> ParseInput for ReflessInput<'d> {
540    type Data = Cow<'d, [u8]>;
541
542    fn push_front(&mut self, data: impl Into<Vec<u8>>) -> crate::Result<()> {
543        let data = data.into();
544        if !data.is_empty() {
545            self.data_mut()?.prefix.push(data);
546        }
547        Ok(())
548    }
549
550    fn read(&mut self, mut data: &mut [u8]) -> crate::Result<()> {
551        match self.data()?.split_at_checked(data.len()) {
552            Some((chunk, rest)) => {
553                self.data = Some(rest);
554                for v in chunk.prefix.iter().rev() {
555                    let part;
556                    (part, data) = data.split_at_mut(v.len());
557                    part.copy_from_slice(v);
558                }
559                data.copy_from_slice(chunk.slice);
560                Ok(())
561            }
562            None => self.end_of_input(),
563        }
564    }
565
566    fn split_n(&mut self, n: usize) -> crate::Result<Self> {
567        match self.data()?.split_at_checked(n) {
568            Some((chunk, rest)) => {
569                self.data = Some(rest);
570                Ok(Self { data: Some(chunk) })
571            }
572            None => self.end_of_input(),
573        }
574    }
575
576    fn skip_n(&mut self, n: usize) -> crate::Result<()> {
577        match self.data()?.split_at_checked(n) {
578            Some((_, rest)) => {
579                self.data = Some(rest);
580                Ok(())
581            }
582            None => self.end_of_input(),
583        }
584    }
585
586    fn find_zero(&mut self) -> crate::Result<usize> {
587        let found = self.data()?.iter().enumerate().find(|(_, x)| **x == 0);
588        match found {
589            Some((at, _)) => Ok(at),
590            None => self.end_of_input(),
591        }
592    }
593
594    fn parse_n_ahead(&mut self, n: usize) -> crate::Result<Vec<u8>> {
595        match self.data()?.split_at_checked(n) {
596            Some((data, _)) => Ok(data.cow().into_owned()),
597            None => self.end_of_input(),
598        }
599    }
600
601    fn compare_ahead(&mut self, c: &[u8]) -> crate::Result<bool> {
602        let data = self.data()?;
603        if data.len() < c.len() {
604            self.end_of_input()
605        } else {
606            Ok(data.starts_with(c))
607        }
608    }
609
610    fn parse_all(self) -> crate::Result<Self::Data> {
611        self.data().map(|data| data.cow())
612    }
613
614    fn empty(self) -> crate::Result<()> {
615        if self.data()?.is_empty() {
616            Ok(())
617        } else {
618            Err(Error::ExtraInputLeft)
619        }
620    }
621
622    fn non_empty(self) -> crate::Result<Option<Self>> {
623        Ok(if self.data()?.is_empty() {
624            None
625        } else {
626            Some(self)
627        })
628    }
629
630    fn remaining(self) -> crate::Result<(Self, usize)> {
631        let len = self.data()?.len();
632        Ok((self, len))
633    }
634
635    fn parse_refless_inline<T: for<'r> ParseInline<ReflessInput<'r>>>(
636        &mut self,
637    ) -> crate::Result<T> {
638        self.parse_inline()
639    }
640
641    fn parse_refless<T: for<'r> Parse<ReflessInput<'r>>>(self) -> crate::Result<T> {
642        self.parse()
643    }
644}
645
646impl<'d, Extra: Clone> ParseInput for Input<'d, Extra> {
647    type Data = Cow<'d, [u8]>;
648
649    fn push_front(&mut self, data: impl Into<Vec<u8>>) -> crate::Result<()> {
650        (**self).push_front(data)
651    }
652
653    fn read(&mut self, data: &mut [u8]) -> crate::Result<()> {
654        (**self).read(data)
655    }
656
657    fn split_n(&mut self, n: usize) -> crate::Result<Self> {
658        Ok(Self {
659            refless: self.refless.split_n(n)?,
660            resolve: self.resolve.clone(),
661            index: self.index,
662            extra: self.extra.clone(),
663        })
664    }
665
666    fn skip_n(&mut self, n: usize) -> crate::Result<()> {
667        (**self).skip_n(n)
668    }
669
670    fn find_zero(&mut self) -> crate::Result<usize> {
671        (**self).find_zero()
672    }
673
674    fn parse_n_ahead(&mut self, n: usize) -> crate::Result<Vec<u8>> {
675        (**self).parse_n_ahead(n)
676    }
677
678    fn compare_ahead(&mut self, c: &[u8]) -> crate::Result<bool> {
679        (**self).compare_ahead(c)
680    }
681
682    fn parse_all(self) -> crate::Result<Self::Data> {
683        self.refless.parse_all()
684    }
685
686    fn empty(self) -> crate::Result<()> {
687        self.refless.empty()
688    }
689
690    fn non_empty(mut self) -> crate::Result<Option<Self>> {
691        self.refless = match self.refless.non_empty()? {
692            Some(refless) => refless,
693            None => return Ok(None),
694        };
695        Ok(Some(self))
696    }
697
698    fn remaining(mut self) -> crate::Result<(Self, usize)> {
699        let remaining;
700        (self.refless, remaining) = self.refless.remaining()?;
701        Ok((self, remaining))
702    }
703
704    fn parse_refless_inline<T: for<'r> ParseInline<ReflessInput<'r>>>(
705        &mut self,
706    ) -> crate::Result<T> {
707        (**self).parse_refless_inline()
708    }
709
710    fn parse_refless<T: for<'r> Parse<ReflessInput<'r>>>(self) -> crate::Result<T> {
711        self.refless.parse_refless()
712    }
713}
714
715impl<'d, Extra: 'static + Clone> PointInput for Input<'d, Extra> {
716    type Extra = Extra;
717    type WithExtra<E: 'static + Clone> = Input<'d, E>;
718
719    fn next_index(&mut self) -> usize {
720        let index = self.index.get();
721        self.index.set(index + 1);
722        index
723    }
724
725    fn resolve_arc_ref(&self) -> &Arc<dyn Resolve> {
726        &self.resolve
727    }
728
729    fn with_resolve(mut self, resolve: Arc<dyn Resolve>) -> Self {
730        self.resolve = Cow::Owned(resolve);
731        self
732    }
733
734    fn extra(&self) -> &Self::Extra {
735        &self.extra
736    }
737
738    fn map_extra<E: 'static + Clone>(
739        self,
740        f: impl FnOnce(&Self::Extra) -> &E,
741    ) -> Self::WithExtra<E> {
742        let Self {
743            refless,
744            resolve,
745            index,
746            extra,
747        } = self;
748        Input {
749            refless,
750            resolve,
751            index,
752            extra: match extra {
753                Cow::Borrowed(extra) => Cow::Borrowed(f(extra)),
754                Cow::Owned(extra) => Cow::Owned(f(&extra).clone()),
755            },
756        }
757    }
758
759    fn replace_extra<E: 'static + Clone>(self, e: E) -> (Extra, Self::WithExtra<E>) {
760        let Self {
761            refless,
762            resolve,
763            index,
764            extra,
765        } = self;
766        (
767            extra.into_owned(),
768            Input {
769                refless,
770                resolve,
771                index,
772                extra: Cow::Owned(e),
773            },
774        )
775    }
776
777    fn with_extra<E: 'static + Clone>(self, extra: E) -> Self::WithExtra<E> {
778        let Self {
779            refless,
780            resolve,
781            index,
782            ..
783        } = self;
784        Input {
785            refless,
786            resolve,
787            index,
788            extra: Cow::Owned(extra),
789        }
790    }
791
792    fn parse_inline_extra<E: 'static + Clone, T: ParseInline<Self::WithExtra<E>>>(
793        &mut self,
794        extra: E,
795    ) -> crate::Result<T> {
796        let Self {
797            refless,
798            resolve,
799            index,
800            ..
801        } = self;
802        let data = refless.data.take();
803        let resolve = resolve.clone();
804        let mut input = Input {
805            refless: ReflessInput { data },
806            resolve,
807            index,
808            extra: Cow::Owned(extra),
809        };
810        let value = input.parse_inline()?;
811        refless.data = input.refless.data.take();
812        Ok(value)
813    }
814}
815
816/// [`Digest::update`]s the hasher.
817impl Output for Sha256 {
818    fn write(&mut self, data: &[u8]) {
819        self.update(data);
820    }
821}
822
823/// Values of this type can be uniquely represented as a `Vec<u8>`.
824pub trait ToOutput {
825    /// Provide object's byte representation to an [`Output`].
826    fn to_output(&self, output: &mut (impl ?Sized + Output));
827
828    /// Return a [`Sha256`] hasher pre-filled with data of this object.
829    fn hasher(&self) -> Sha256 {
830        self.output()
831    }
832
833    /// [`Hash`] of (real, i.e. serialized) data of this object.
834    #[must_use]
835    fn data_hash(&self) -> Hash {
836        self.output()
837    }
838
839    /// "Mangle hash" of the object. This is used to introduce runtime distinction between
840    /// data-identical objects similarly to compile-time [`Tagged::HASH`].
841    fn mangle_hash(&self) -> Hash {
842        Mangled(self).data_hash()
843    }
844
845    /// Construct an [`Output`], possibly finalising it afterwards.
846    ///
847    /// For an example of a [`FromOutput`] see [`Hash`].
848    fn output<T: FromOutput<Output: Default>>(&self) -> T {
849        let mut output = T::Output::default();
850        self.to_output(&mut output);
851        output.into()
852    }
853
854    /// Collect this object's data (serialize the object).
855    fn vec(&self) -> Vec<u8> {
856        self.output()
857    }
858}
859
860/// Marker trait indicating that [`ToOutput`] result cannot be extended (no value, when represented
861/// as a `Vec<u8>`, may be a prefix of another value). Effectively means prefix property.
862pub trait InlineOutput: ToOutput {
863    /// Specialisation point to allow types like [`u8`] to provide better serialisation
864    /// implementation for containers like [`Vec<u8>`].
865    fn slice_to_output(slice: &[Self], output: &mut (impl ?Sized + Output))
866    where
867        Self: Sized,
868    {
869        slice.iter_to_output(output);
870    }
871}
872
873/// Provide [`ToOutput`] for [`Option<Self>`].
874pub trait OptionOutput {
875    /// Provide [`ToOutput::to_output`] for [`Option<Self>`].
876    fn to_option_output(option: Option<&Self>, output: &mut (impl ?Sized + Output));
877}
878
879/// Provide [`Parse`] for [`Option<Self>`].
880pub trait OptionParse<I: ParseInput>: Parse<I> {
881    /// Provide [`Parse::parse`] for [`Option<Self>`].
882    fn parse_option(input: I) -> crate::Result<Option<Self>>;
883}
884
885/// Provide [`ParseInline`] for [`Option<Self>`].
886pub trait OptionParseInline<I: ParseInput>: OptionParse<I> + ParseInline<I> {
887    /// Provide [`ParseInline::parse_inline`] for [`Option<Self>`].
888    fn parse_option_inline(input: &mut I) -> crate::Result<Option<Self>>;
889}
890
891/// [`ToOutput`] representing an object's [`Hash`]es list.
892pub struct Hashes<T>(pub T);
893
894impl<T: ListHashes> ToOutput for Hashes<T> {
895    fn to_output(&self, output: &mut (impl ?Sized + Output)) {
896        self.0.list_hashes(&mut |hash| hash.to_output(output));
897    }
898}
899
900/// Semantically part of [`Topological`] but decoupled for simpler recursive bounds.
901pub trait ListHashes {
902    /// [`Hash`]-only part of [`Topological::traverse`].
903    fn list_hashes(&self, f: &mut (impl ?Sized + FnMut(Hash))) {
904        let _ = f;
905    }
906
907    /// [`Hash`] of all [`Hash`]es the object refers to other objects by.
908    fn topology_hash(&self) -> Hash {
909        Hashes(self).data_hash()
910    }
911
912    /// How many others this object refers to.
913    fn point_count(&self) -> usize {
914        let mut count = 0;
915        self.list_hashes(&mut |_| count += 1);
916        count
917    }
918}
919
920/// Central `trait` responsible for providing access to walking the object tree.
921pub trait Topological: ListHashes {
922    /// List what objects this one refers to.
923    ///
924    /// Each referred object is also expected to be [`Traversible`].
925    fn traverse(&self, visitor: &mut (impl ?Sized + PointVisitor)) {
926        let _ = visitor;
927    }
928
929    /// Collect references into a dynamically-typed list.
930    fn topology(&self) -> TopoVec {
931        let mut topology = TopoVec::with_capacity(self.point_count());
932        self.traverse(&mut topology);
933        topology
934    }
935
936    /// Useful in [`Resolve::resolve`] and [`FetchBytes::fetch_bytes`].
937    fn byte_node(&self) -> ByteNode
938    where
939        Self: ToOutput,
940    {
941        (self.vec(), self.to_resolve())
942    }
943
944    /// Reconstruct a [`Resolve`] usable for [`Parse::parse`]ing this object based on references.
945    fn to_resolve(&self) -> Arc<dyn Resolve> {
946        struct ByTopology {
947            topology: TopoVec,
948            topology_hash: Hash,
949        }
950
951        impl Drop for ByTopology {
952            fn drop(&mut self) {
953                while let Some(singular) = self.topology.pop() {
954                    if let Some(resolve) = singular.try_unwrap_resolve()
955                        && let Some(topology) = &mut resolve.into_topovec()
956                    {
957                        self.topology.append(topology);
958                    }
959                }
960            }
961        }
962
963        impl ByTopology {
964            fn try_resolve(&'_ self, address: Address) -> Result<FailFuture<'_, ByteNode>> {
965                let point = self
966                    .topology
967                    .get(address.index)
968                    .ok_or(Error::AddressOutOfBounds)?;
969                if point.hash() != address.hash {
970                    Err(Error::ResolutionMismatch)
971                } else {
972                    Ok(point.fetch_bytes())
973                }
974            }
975
976            fn try_resolve_data(&'_ self, address: Address) -> Result<FailFuture<'_, Vec<u8>>> {
977                let point = self
978                    .topology
979                    .get(address.index)
980                    .ok_or(Error::AddressOutOfBounds)?;
981                if point.hash() != address.hash {
982                    Err(Error::ResolutionMismatch)
983                } else {
984                    Ok(point.fetch_data())
985                }
986            }
987        }
988
989        impl Resolve for ByTopology {
990            fn resolve(
991                &'_ self,
992                address: Address,
993                _: &Arc<dyn Resolve>,
994            ) -> FailFuture<'_, ByteNode> {
995                self.try_resolve(address)
996                    .map_err(Err)
997                    .map_err(ready)
998                    .map_err(Box::pin)
999                    .unwrap_or_else(|x| x)
1000            }
1001
1002            fn resolve_data(&'_ self, address: Address) -> FailFuture<'_, Vec<u8>> {
1003                self.try_resolve_data(address)
1004                    .map_err(Err)
1005                    .map_err(ready)
1006                    .map_err(Box::pin)
1007                    .unwrap_or_else(|x| x)
1008            }
1009
1010            fn try_resolve_local(
1011                &self,
1012                address: Address,
1013                _: &Arc<dyn Resolve>,
1014            ) -> Result<Option<ByteNode>> {
1015                let point = self
1016                    .topology
1017                    .get(address.index)
1018                    .ok_or(Error::AddressOutOfBounds)?;
1019                if point.hash() != address.hash {
1020                    Err(Error::ResolutionMismatch)
1021                } else {
1022                    point.fetch_bytes_local()
1023                }
1024            }
1025
1026            fn topology_hash(&self) -> Option<Hash> {
1027                Some(self.topology_hash)
1028            }
1029
1030            fn into_topovec(self: Arc<Self>) -> Option<TopoVec> {
1031                Arc::try_unwrap(self)
1032                    .ok()
1033                    .as_mut()
1034                    .map(|Self { topology, .. }| std::mem::take(topology))
1035            }
1036        }
1037
1038        let topology = self.topology();
1039        let topology_hash = topology.data_hash();
1040        for singular in &topology {
1041            if let Some(resolve) = singular.as_resolve()
1042                && (**resolve).topology_hash() == Some(topology_hash)
1043            {
1044                return resolve.clone();
1045            }
1046        }
1047        Arc::new(ByTopology {
1048            topology,
1049            topology_hash,
1050        })
1051    }
1052}
1053
1054/// Compile-time type information used to differentiate objects even when they have same serialised
1055/// data. Typically empty.
1056pub trait Tagged {
1057    const TAGS: Tags = Tags(&[], &[]);
1058    const HASH: Hash = Self::TAGS.hash();
1059}
1060
1061pub trait TagsHash {
1062    fn tags_hash(&self) -> Hash;
1063}
1064
1065impl<T: ?Sized + Tagged> TagsHash for T {
1066    fn tags_hash(&self) -> Hash {
1067        Self::HASH
1068    }
1069}
1070
1071pub trait ParseSlice: for<'a> Parse<Input<'a>> {
1072    fn parse_slice(slice: &[u8], resolve: &Arc<dyn Resolve>) -> crate::Result<Self> {
1073        Self::parse_slice_extra(slice, resolve, &())
1074    }
1075
1076    fn reparse(&self) -> crate::Result<Self>
1077    where
1078        Self: Traversible,
1079    {
1080        self.reparse_extra(&())
1081    }
1082}
1083
1084impl<T: for<'a> Parse<Input<'a>>> ParseSlice for T {}
1085
1086pub trait ParseSliceExtra<Extra: Clone>: for<'a> Parse<Input<'a, Extra>> {
1087    fn parse_slice_extra(
1088        slice: &[u8],
1089        resolve: &Arc<dyn Resolve>,
1090        extra: &Extra,
1091    ) -> crate::Result<Self> {
1092        let input = Input {
1093            refless: ReflessInput {
1094                data: Some(ReflessData {
1095                    slice,
1096                    prefix: Vec::new(),
1097                }),
1098            },
1099            resolve: Cow::Borrowed(resolve),
1100            index: &Cell::new(0),
1101            extra: Cow::Borrowed(extra),
1102        };
1103        let object = Self::parse(input)?;
1104        Ok(object)
1105    }
1106
1107    fn reparse_extra(&self, extra: &Extra) -> crate::Result<Self>
1108    where
1109        Self: Traversible,
1110    {
1111        Self::parse_slice_extra(&self.vec(), &self.to_resolve(), extra)
1112    }
1113}
1114
1115impl<T: for<'a> Parse<Input<'a, Extra>>, Extra: Clone> ParseSliceExtra<Extra> for T {}
1116
1117pub trait ParseAs<'a> {
1118    fn parse_as<T: ParseSlice>(&self) -> crate::Result<T>;
1119}
1120
1121impl<'a> ParseAs<'a> for &'a [u8] {
1122    fn parse_as<T: ParseSlice>(&self) -> crate::Result<T> {
1123        T::parse_slice(self, &(Arc::new(Vec::new()) as _))
1124    }
1125}
1126
1127pub trait ParseAsExtra<'a, Extra: Clone> {
1128    fn parse_as_extra<T: ParseSliceExtra<Extra>>(&self, extra: &Extra) -> crate::Result<T>;
1129}
1130
1131impl<'a, Extra: Clone> ParseAsExtra<'a, Extra> for &'a [u8] {
1132    fn parse_as_extra<T: ParseSliceExtra<Extra>>(&self, extra: &Extra) -> crate::Result<T> {
1133        T::parse_slice_extra(self, &(Arc::new(Vec::new()) as _), extra)
1134    }
1135}
1136
1137#[derive(Debug, ToOutput, Default)]
1138pub struct DiffHashes {
1139    pub tags: Hash,
1140    pub topology: Hash,
1141    pub mangle: Hash,
1142}
1143
1144#[derive(Debug, ToOutput)]
1145pub struct WithHash<'a, T: ?Sized> {
1146    pub diff: Hash,
1147    pub data: &'a T,
1148}
1149
1150pub trait FullHash: ToOutput + ListHashes + Tagged {
1151    fn diff_hashes(&self) -> DiffHashes {
1152        DiffHashes {
1153            tags: self.tags_hash(),
1154            topology: self.topology_hash(),
1155            mangle: self.mangle_hash(),
1156        }
1157    }
1158
1159    fn with_hash(&self) -> WithHash<'_, Self> {
1160        WithHash {
1161            diff: self.diff_hashes().data_hash(),
1162            data: self,
1163        }
1164    }
1165
1166    fn full_hash(&self) -> Hash {
1167        self.with_hash().data_hash()
1168    }
1169}
1170
1171impl<T: ?Sized + ToOutput + ListHashes + Tagged> FullHash for T {}
1172
1173pub trait DefaultHash: FullHash + Default {
1174    fn default_hash() -> Hash {
1175        Self::default().full_hash()
1176    }
1177}
1178
1179impl<T: FullHash + Default> DefaultHash for T {}
1180
1181pub trait Traversible: 'static + Sized + Send + Sync + FullHash + Topological {
1182    fn local(self) -> Arc<dyn SingularFetch<T = Self>>
1183    where
1184        Self: Clone,
1185    {
1186        Arc::new(crate::local_fetch::Local(self))
1187    }
1188}
1189
1190impl<T: 'static + Send + Sync + FullHash + Topological> Traversible for T {}
1191
1192pub trait Object<Extra = ()>: Traversible + for<'a> Parse<Input<'a, Extra>> {}
1193
1194impl<T: Traversible + for<'a> Parse<Input<'a, Extra>>, Extra> Object<Extra> for T {}
1195
1196pub trait Inline<Extra = ()>:
1197    Object<Extra> + InlineOutput + for<'a> ParseInline<Input<'a, Extra>>
1198{
1199}
1200
1201impl<T: Object<Extra> + InlineOutput + for<'a> ParseInline<Input<'a, Extra>>, Extra> Inline<Extra>
1202    for T
1203{
1204}
1205
1206pub trait Component: InlineOutput + Traversible + Clone {}
1207
1208impl<T: InlineOutput + Traversible + Clone> Component for T {}
1209
1210pub struct Tags(pub &'static [&'static str], pub &'static [&'static Self]);
1211
1212const fn bytes_compare(l: &[u8], r: &[u8]) -> std::cmp::Ordering {
1213    let mut i = 0;
1214    while i < l.len() && i < r.len() {
1215        if l[i] > r[i] {
1216            return std::cmp::Ordering::Greater;
1217        } else if l[i] < r[i] {
1218            return std::cmp::Ordering::Less;
1219        } else {
1220            i += 1;
1221        }
1222    }
1223    if l.len() > r.len() {
1224        std::cmp::Ordering::Greater
1225    } else if l.len() < r.len() {
1226        std::cmp::Ordering::Less
1227    } else {
1228        std::cmp::Ordering::Equal
1229    }
1230}
1231
1232const fn str_compare(l: &str, r: &str) -> std::cmp::Ordering {
1233    bytes_compare(l.as_bytes(), r.as_bytes())
1234}
1235
1236impl Tags {
1237    const fn min_out(&self, strict_min: Option<&str>, min: &mut Option<&'static str>) {
1238        {
1239            let mut i = 0;
1240            while i < self.0.len() {
1241                let candidate = self.0[i];
1242                i += 1;
1243                if let Some(strict_min) = strict_min
1244                    && str_compare(candidate, strict_min).is_le()
1245                {
1246                    continue;
1247                }
1248                if let Some(min) = min
1249                    && str_compare(candidate, min).is_ge()
1250                {
1251                    continue;
1252                }
1253                *min = Some(candidate);
1254            }
1255        }
1256        {
1257            let mut i = 0;
1258            while i < self.1.len() {
1259                self.1[i].min_out(strict_min, min);
1260                i += 1;
1261            }
1262        }
1263        if let Some(l) = min
1264            && let Some(r) = strict_min
1265        {
1266            assert!(str_compare(l, r).is_gt());
1267        }
1268    }
1269
1270    const fn min(&self, strict_min: Option<&str>) -> Option<&'static str> {
1271        let mut min = None;
1272        self.min_out(strict_min, &mut min);
1273        min
1274    }
1275
1276    const fn const_hash(&self, mut hasher: sha2_const::Sha256) -> sha2_const::Sha256 {
1277        let mut last = None;
1278        let mut i = 0;
1279        while let Some(next) = self.min(last) {
1280            i += 1;
1281            if i > 1000 {
1282                panic!("{}", next);
1283            }
1284            hasher = hasher.update(next.as_bytes());
1285            last = Some(next);
1286        }
1287        hasher
1288    }
1289
1290    const fn hash(&self) -> Hash {
1291        Hash::from_sha256(self.const_hash(sha2_const::Sha256::new()).finalize())
1292    }
1293}
1294
1295#[test]
1296fn min_out_respects_bounds() {
1297    let mut min = None;
1298    Tags(&["c", "b", "a"], &[]).min_out(Some("a"), &mut min);
1299    assert_eq!(min, Some("b"));
1300}
1301
1302#[test]
1303fn const_hash() {
1304    assert_ne!(Tags(&["a", "b"], &[]).hash(), Tags(&["a"], &[]).hash());
1305    assert_eq!(
1306        Tags(&["a", "b"], &[]).hash(),
1307        Tags(&["a"], &[&Tags(&["b"], &[])]).hash(),
1308    );
1309    assert_eq!(Tags(&["a", "b"], &[]).hash(), Tags(&["b", "a"], &[]).hash());
1310    assert_eq!(Tags(&["a", "a"], &[]).hash(), Tags(&["a"], &[]).hash());
1311}
1312
1313pub trait Topology: Resolve {
1314    fn len(&self) -> usize;
1315    fn get(&self, index: usize) -> Option<&Arc<dyn Singular>>;
1316
1317    fn is_empty(&self) -> bool {
1318        self.len() == 0
1319    }
1320}
1321
1322pub trait Singular: Send + Sync + FetchBytes {
1323    fn hash(&self) -> Hash;
1324    fn parse_checked<T: FullHash, E: ExtraFor<T>>(
1325        &self,
1326        data: &[u8],
1327        resolve: &Arc<dyn Resolve>,
1328        extra: &E,
1329    ) -> object_rainbow::Result<T>
1330    where
1331        Self: Sized,
1332    {
1333        extra.parse_checked(self.hash(), data, resolve)
1334    }
1335}
1336
1337pub trait SingularFetch: Singular + Fetch {
1338    fn fetch_checked<'a>(&'a self) -> FailFuture<'a, Self::T>
1339    where
1340        Self: Sized,
1341        Self::T: 'a + FullHash,
1342        Self: AsExtra<Extra: 'a + Send + Sync + ExtraFor<Self::T>>,
1343    {
1344        Box::pin(async move {
1345            let (data, resolve) = self.fetch_bytes().await?;
1346            self.parse_checked(&data, &resolve, self.as_extra())
1347        })
1348    }
1349    fn try_fetch_local_checked(&self) -> object_rainbow::Result<Option<Self::T>>
1350    where
1351        Self: Sized,
1352        Self::T: FullHash,
1353        Self: AsExtra<Extra: ExtraFor<Self::T>>,
1354    {
1355        let Some((data, resolve)) = self.fetch_bytes_local()? else {
1356            return Ok(None);
1357        };
1358        self.parse_checked(&data, &resolve, self.as_extra())
1359            .map(Some)
1360    }
1361    fn fetch_checked_join<'a, E: 'a + Send + Sync + ExtraFor<Self::T>>(
1362        &'a self,
1363        extra: impl 'a + Send + Future<Output = object_rainbow::Result<E>>,
1364    ) -> FailFuture<'a, Self::T>
1365    where
1366        Self: Sized,
1367        Self::T: 'a + FullHash,
1368    {
1369        Box::pin(async move {
1370            let ((data, resolve), extra) = (self.fetch_bytes(), extra).try_join().await?;
1371            self.parse_checked(&data, &resolve, &extra)
1372        })
1373    }
1374}
1375
1376impl<T: ?Sized + Singular + Fetch> SingularFetch for T {}
1377
1378impl ToOutput for dyn '_ + Singular {
1379    fn to_output(&self, output: &mut (impl ?Sized + Output)) {
1380        self.hash().to_output(output);
1381    }
1382}
1383
1384impl InlineOutput for dyn '_ + Singular {}
1385
1386impl ListHashes for dyn '_ + Singular {
1387    fn list_hashes(&self, f: &mut (impl ?Sized + FnMut(Hash))) {
1388        f(self.hash());
1389    }
1390
1391    fn point_count(&self) -> usize {
1392        1
1393    }
1394}
1395
1396impl<T> ToOutput for dyn '_ + SingularFetch<T = T> {
1397    fn to_output(&self, output: &mut (impl ?Sized + Output)) {
1398        self.hash().to_output(output);
1399    }
1400}
1401
1402impl<T> InlineOutput for dyn '_ + SingularFetch<T = T> {}
1403
1404impl<T: Tagged> Tagged for dyn '_ + SingularFetch<T = T> {
1405    const TAGS: Tags = T::TAGS;
1406    const HASH: Hash = T::HASH;
1407}
1408
1409impl<T> ListHashes for dyn '_ + SingularFetch<T = T> {
1410    fn list_hashes(&self, f: &mut (impl ?Sized + FnMut(Hash))) {
1411        f(self.hash());
1412    }
1413
1414    fn point_count(&self) -> usize {
1415        1
1416    }
1417}
1418
1419pub type TopoVec = Vec<Arc<dyn Singular>>;
1420
1421impl<T: Traversible> Topological for Arc<dyn SingularFetch<T = T>> {
1422    fn traverse(&self, visitor: &mut (impl ?Sized + PointVisitor)) {
1423        visitor.visit(self);
1424    }
1425}
1426
1427impl PointVisitor for TopoVec {
1428    fn visit(&mut self, point: &(impl 'static + SingularFetch<T: Traversible> + Clone)) {
1429        self.push(Arc::new(point.clone()));
1430    }
1431}
1432
1433impl Resolve for TopoVec {
1434    fn resolve<'a>(
1435        &'a self,
1436        address: Address,
1437        _: &'a Arc<dyn Resolve>,
1438    ) -> FailFuture<'a, ByteNode> {
1439        Box::pin(async move {
1440            let singular = self.get(address.index).ok_or(Error::AddressOutOfBounds)?;
1441            if singular.hash() != address.hash {
1442                Err(Error::FullHashMismatch)
1443            } else {
1444                singular.fetch_bytes().await
1445            }
1446        })
1447    }
1448
1449    fn resolve_data(&'_ self, address: Address) -> FailFuture<'_, Vec<u8>> {
1450        Box::pin(async move {
1451            let singular = self.get(address.index).ok_or(Error::AddressOutOfBounds)?;
1452            if singular.hash() != address.hash {
1453                Err(Error::FullHashMismatch)
1454            } else {
1455                singular.fetch_data().await
1456            }
1457        })
1458    }
1459
1460    fn try_resolve_local(
1461        &self,
1462        address: Address,
1463        _: &Arc<dyn Resolve>,
1464    ) -> Result<Option<ByteNode>> {
1465        let singular = self.get(address.index).ok_or(Error::AddressOutOfBounds)?;
1466        if singular.hash() != address.hash {
1467            Err(Error::FullHashMismatch)
1468        } else {
1469            singular.fetch_bytes_local()
1470        }
1471    }
1472
1473    fn topology_hash(&self) -> Option<Hash> {
1474        Some(self.data_hash())
1475    }
1476
1477    fn into_topovec(self: Arc<Self>) -> Option<TopoVec> {
1478        Arc::try_unwrap(self).ok()
1479    }
1480}
1481
1482impl Topology for TopoVec {
1483    fn len(&self) -> usize {
1484        self.len()
1485    }
1486
1487    fn get(&self, index: usize) -> Option<&Arc<dyn Singular>> {
1488        (**self).get(index)
1489    }
1490}
1491
1492pub trait ParseSliceRefless: for<'a> Parse<ReflessInput<'a>> {
1493    fn parse_slice_refless(slice: &[u8]) -> crate::Result<Self> {
1494        let input = ReflessInput {
1495            data: Some(ReflessData {
1496                slice,
1497                prefix: Vec::new(),
1498            }),
1499        };
1500        let object = Self::parse(input)?;
1501        Ok(object)
1502    }
1503}
1504
1505impl<T: for<'a> Parse<ReflessInput<'a>>> ParseSliceRefless for T {}
1506
1507pub trait ReflessObject:
1508    'static + Sized + Send + Sync + ToOutput + Tagged + for<'a> Parse<ReflessInput<'a>>
1509{
1510}
1511
1512impl<T: 'static + Sized + Send + Sync + ToOutput + Tagged + for<'a> Parse<ReflessInput<'a>>>
1513    ReflessObject for T
1514{
1515}
1516
1517pub trait ReflessInline:
1518    ReflessObject + InlineOutput + for<'a> ParseInline<ReflessInput<'a>>
1519{
1520}
1521
1522impl<T: ReflessObject + InlineOutput + for<'a> ParseInline<ReflessInput<'a>>> ReflessInline for T {}
1523
1524pub trait FromOutput: From<Self::Output> {
1525    type Output: Output;
1526}
1527
1528impl<T: Output> FromOutput for T {
1529    type Output = T;
1530}
1531
1532pub trait Output {
1533    fn write(&mut self, data: &[u8]);
1534    fn is_mangling(&self) -> bool {
1535        false
1536    }
1537    fn is_real(&self) -> bool {
1538        !self.is_mangling()
1539    }
1540}
1541
1542pub trait OutputExt: Output {
1543    fn as_write(&mut self) -> AsWrite<'_, Self> {
1544        AsWrite { output: self }
1545    }
1546}
1547
1548impl<T: ?Sized + Output> OutputExt for T {}
1549
1550/// [`std::io::Write`] representation of an [`Output`].
1551pub struct AsWrite<'a, O: ?Sized> {
1552    output: &'a mut O,
1553}
1554
1555/// This implementation is guaranteed to never error (but might panic).
1556impl<O: ?Sized + Output> std::io::Write for AsWrite<'_, O> {
1557    fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
1558        self.output.write(data);
1559        Ok(data.len())
1560    }
1561
1562    fn flush(&mut self) -> std::io::Result<()> {
1563        Ok(())
1564    }
1565}
1566
1567impl Output for Vec<u8> {
1568    fn write(&mut self, data: &[u8]) {
1569        self.extend_from_slice(data);
1570    }
1571}
1572
1573struct MangleOutput<'a, T: ?Sized>(&'a mut T);
1574
1575impl<'a, T: ?Sized + Output> MangleOutput<'a, T> {
1576    fn new(output: &'a mut T) -> Self {
1577        assert!(output.is_real());
1578        assert!(!output.is_mangling());
1579        Self(output)
1580    }
1581}
1582
1583impl<T: ?Sized + Output> Output for MangleOutput<'_, T> {
1584    fn write(&mut self, data: &[u8]) {
1585        self.0.write(data);
1586    }
1587
1588    fn is_mangling(&self) -> bool {
1589        true
1590    }
1591}
1592
1593pub struct Mangled<T: ?Sized>(T);
1594
1595impl<T: ?Sized + ToOutput> ToOutput for Mangled<T> {
1596    fn to_output(&self, output: &mut (impl ?Sized + Output)) {
1597        self.0.to_output(&mut MangleOutput::new(output));
1598    }
1599}
1600
1601#[doc(hidden)]
1602pub trait SizeSumHelper {
1603    const SIZE_ARRAY: usize;
1604    type SizeArray;
1605}
1606
1607pub trait Size {
1608    const SIZE: usize = <Self::Size as Unsigned>::USIZE;
1609    type Size: Unsigned;
1610}
1611
1612pub trait SizeExt: Size<Size: ArrayLength> + ToOutput {
1613    fn to_array(&self) -> GenericArray<u8, Self::Size> {
1614        struct ArrayOutput<'a> {
1615            data: &'a mut [u8],
1616            offset: usize,
1617        }
1618
1619        impl ArrayOutput<'_> {
1620            fn finalize(self) {
1621                assert_eq!(self.offset, self.data.len());
1622            }
1623        }
1624
1625        impl Output for ArrayOutput<'_> {
1626            fn write(&mut self, data: &[u8]) {
1627                self.data[self.offset..][..data.len()].copy_from_slice(data);
1628                self.offset += data.len();
1629            }
1630        }
1631
1632        let mut array = GenericArray::default();
1633        let mut output = ArrayOutput {
1634            data: &mut array,
1635            offset: 0,
1636        };
1637        self.to_output(&mut output);
1638        output.finalize();
1639        array
1640    }
1641
1642    fn reinterpret<T: FromSized<Size = Self::Size>>(&self) -> T {
1643        T::from_sized(&self.to_array())
1644    }
1645}
1646
1647impl<T: Size<Size: ArrayLength> + ToOutput> SizeExt for T {}
1648
1649pub trait FromSized: Size<Size: ArrayLength> {
1650    fn from_sized(data: &GenericArray<u8, Self::Size>) -> Self;
1651}
1652
1653impl<
1654    A: FromSized<Size = An>,
1655    B: FromSized<Size = Bn>,
1656    An,
1657    Bn: Add<An, Output: ArrayLength + Sub<An, Output = Bn>>,
1658> FromSized for (A, B)
1659{
1660    fn from_sized(data: &GenericArray<u8, Self::Size>) -> Self {
1661        let (a, b) = data.split();
1662        (A::from_sized(a), B::from_sized(b))
1663    }
1664}
1665
1666macro_rules! from_sized_tuple {
1667    (($($t:ident),*), ($($x:ident),*) $(,)?) => {
1668        impl<A, $($t),*, N> FromSized for (A, $($t),*)
1669        where
1670            (A, ($($t),*)): FromSized<Size = N>,
1671            Self: Size<Size = N>,
1672        {
1673            fn from_sized(data: &GenericArray<u8, Self::Size>) -> Self {
1674                let (a, ($($x),*)) = FromSized::from_sized(data);
1675                (a, $($x),*)
1676            }
1677        }
1678    };
1679}
1680
1681from_sized_tuple!((B, C), (b, c));
1682from_sized_tuple!((B, C, D), (b, c, d));
1683from_sized_tuple!((B, C, D, E), (b, c, d, e));
1684from_sized_tuple!((B, C, D, E, F), (b, c, d, e, f));
1685from_sized_tuple!((B, C, D, E, F, G), (b, c, d, e, f, g));
1686from_sized_tuple!((B, C, D, E, F, G, H), (b, c, d, e, f, g, h));
1687from_sized_tuple!((B, C, D, E, F, G, H, I), (b, c, d, e, f, g, h, i));
1688from_sized_tuple!((B, C, D, E, F, G, H, I, J), (b, c, d, e, f, g, h, i, j));
1689from_sized_tuple!(
1690    (B, C, D, E, F, G, H, I, J, K),
1691    (b, c, d, e, f, g, h, i, j, k),
1692);
1693from_sized_tuple!(
1694    (B, C, D, E, F, G, H, I, J, K, L),
1695    (b, c, d, e, f, g, h, i, j, k, l),
1696);
1697
1698pub trait RainbowIterator: Sized + IntoIterator {
1699    fn iter_to_output(self, output: &mut (impl ?Sized + Output))
1700    where
1701        Self::Item: InlineOutput,
1702    {
1703        self.into_iter().for_each(|item| item.to_output(output));
1704    }
1705
1706    fn iter_list_hashes(self, f: &mut (impl ?Sized + FnMut(Hash)))
1707    where
1708        Self::Item: ListHashes,
1709    {
1710        self.into_iter().for_each(|item| item.list_hashes(f));
1711    }
1712
1713    fn iter_traverse(self, visitor: &mut (impl ?Sized + PointVisitor))
1714    where
1715        Self::Item: Topological,
1716    {
1717        self.into_iter().for_each(|item| item.traverse(visitor));
1718    }
1719
1720    fn iter_bytes_cmp(self, other: impl IntoIterator<Item = Self::Item>) -> Ordering
1721    where
1722        Self::Item: ByteOrd,
1723    {
1724        self.into_iter()
1725            .map(OrderedByBytes)
1726            .cmp(other.into_iter().map(OrderedByBytes))
1727    }
1728}
1729
1730pub trait ParseInput: Sized {
1731    type Data: AsRef<[u8]> + Deref<Target = [u8]> + Into<Vec<u8>>;
1732    fn push_front(&mut self, data: impl Into<Vec<u8>>) -> crate::Result<()>;
1733    fn read(&mut self, data: &mut [u8]) -> crate::Result<()>;
1734    fn parse_chunk<const N: usize>(&mut self) -> crate::Result<[u8; N]> {
1735        let mut chunk = [0; _];
1736        self.read(&mut chunk)?;
1737        Ok(chunk)
1738    }
1739    fn split_n(&mut self, n: usize) -> crate::Result<Self>;
1740    fn skip_n(&mut self, n: usize) -> crate::Result<()>;
1741    fn find_zero(&mut self) -> crate::Result<usize>;
1742    fn parse_n_ahead(&mut self, n: usize) -> crate::Result<Vec<u8>>;
1743    fn compare_ahead(&mut self, c: &[u8]) -> crate::Result<bool>;
1744    fn split_parse<T: Parse<Self>>(&mut self, n: usize) -> crate::Result<T> {
1745        self.split_n(n)?.parse()
1746    }
1747    fn parse_zero_terminated<T: Parse<Self>>(&mut self) -> crate::Result<(Vec<u8>, T)> {
1748        let n = self.find_zero()?;
1749        let data = self.parse_n_ahead(n)?;
1750        let value = self.split_parse(n)?;
1751        self.skip_n(1)?;
1752        Ok((data, value))
1753    }
1754    fn compare_skip(&mut self, c: &[u8]) -> Result<bool> {
1755        let matches = self.compare_ahead(c)?;
1756        if matches {
1757            self.skip_n(c.len())?
1758        }
1759        Ok(matches)
1760    }
1761    fn parse_compare<T: Parse<Self>>(mut self, c: &[u8]) -> Result<Option<T>> {
1762        if self.compare_skip(c)? {
1763            self.empty()?;
1764            Ok(None)
1765        } else {
1766            Ok(Some(self.parse()?))
1767        }
1768    }
1769    fn parse_compare_inline<T: ParseInline<Self>>(&mut self, c: &[u8]) -> Result<Option<T>> {
1770        if self.compare_skip(c)? {
1771            Ok(None)
1772        } else {
1773            Ok(Some(self.parse_inline()?))
1774        }
1775    }
1776    fn parse_all(self) -> crate::Result<Self::Data>;
1777    fn empty(self) -> crate::Result<()>;
1778    fn non_empty(self) -> crate::Result<Option<Self>>;
1779    fn remaining(self) -> crate::Result<(Self, usize)>;
1780
1781    fn consume(self, f: impl FnMut(&mut Self) -> crate::Result<()>) -> crate::Result<()> {
1782        self.collect(f)
1783    }
1784
1785    fn parse_collect<T: ParseInline<Self>, B: FromIterator<T>>(self) -> crate::Result<B> {
1786        self.collect(|input| input.parse_inline())
1787    }
1788
1789    fn collect<T, B: FromIterator<T>>(
1790        self,
1791        f: impl FnMut(&mut Self) -> crate::Result<T>,
1792    ) -> crate::Result<B> {
1793        self.iter(f).collect()
1794    }
1795
1796    fn iter<T>(
1797        self,
1798        mut f: impl FnMut(&mut Self) -> crate::Result<T>,
1799    ) -> impl Iterator<Item = crate::Result<T>> {
1800        let mut state = Some(self);
1801        std::iter::from_fn(move || {
1802            let mut input = match state.take()?.non_empty() {
1803                Ok(input) => input?,
1804                Err(e) => return Some(Err(e)),
1805            };
1806            let item = f(&mut input);
1807            state = Some(input);
1808            Some(item)
1809        })
1810    }
1811
1812    fn parse_inline<T: ParseInline<Self>>(&mut self) -> crate::Result<T> {
1813        T::parse_inline(self)
1814    }
1815
1816    fn parse<T: Parse<Self>>(self) -> crate::Result<T> {
1817        T::parse(self)
1818    }
1819
1820    fn parse_vec<T: ParseInline<Self>>(self) -> crate::Result<Vec<T>> {
1821        T::parse_vec(self)
1822    }
1823
1824    fn parse_vec_n<T: ParseInline<Self>>(&mut self, n: usize) -> crate::Result<Vec<T>> {
1825        T::parse_vec_n(self, n)
1826    }
1827
1828    fn parse_array<T: ParseInline<Self>, const N: usize>(&mut self) -> crate::Result<[T; N]> {
1829        T::parse_array(self)
1830    }
1831
1832    fn parse_generic_array<T: ParseInline<Self>, N: ArrayLength>(
1833        &mut self,
1834    ) -> crate::Result<GenericArray<T, N>> {
1835        T::parse_generic_array(self)
1836    }
1837
1838    fn as_read<T, E>(
1839        &mut self,
1840        f: impl FnOnce(AsRead<'_, Self>) -> std::result::Result<T, E>,
1841    ) -> crate::Result<T>
1842    where
1843        Error: From<E>,
1844    {
1845        let result = f(AsRead { input: self })?;
1846        self.noop()?;
1847        Ok(result)
1848    }
1849
1850    fn noop(&mut self) -> crate::Result<()> {
1851        self.read(&mut [])
1852    }
1853
1854    fn parse_refless_inline<T: for<'r> ParseInline<ReflessInput<'r>>>(
1855        &mut self,
1856    ) -> crate::Result<T>;
1857
1858    fn parse_refless<T: for<'r> Parse<ReflessInput<'r>>>(self) -> crate::Result<T>;
1859
1860    fn parse_as_inline<T>(
1861        mut self,
1862        f: impl FnOnce(&mut Self) -> crate::Result<T>,
1863    ) -> crate::Result<T> {
1864        let object = f(&mut self)?;
1865        self.empty()?;
1866        Ok(object)
1867    }
1868}
1869
1870/// [`std::io::Read`] representation of a [`ParseInput`].
1871pub struct AsRead<'a, I> {
1872    input: &'a mut I,
1873}
1874
1875impl<I: ParseInput> std::io::Read for AsRead<'_, I> {
1876    fn read(&mut self, data: &mut [u8]) -> std::io::Result<usize> {
1877        self.read_exact(data)?;
1878        Ok(data.len())
1879    }
1880
1881    fn read_exact(&mut self, data: &mut [u8]) -> std::io::Result<()> {
1882        self.input.read(data)?;
1883        Ok(())
1884    }
1885
1886    fn read_to_end(&mut self, _: &mut Vec<u8>) -> std::io::Result<usize> {
1887        Err(std::io::ErrorKind::Unsupported.into())
1888    }
1889}
1890
1891pub trait PointInput: ParseInput {
1892    type Extra: 'static + Clone;
1893    type WithExtra<E: 'static + Clone>: PointInput<Extra = E, WithExtra<Self::Extra> = Self>;
1894    fn next_index(&mut self) -> usize;
1895    fn resolve_arc_ref(&self) -> &Arc<dyn Resolve>;
1896    fn resolve(&self) -> Arc<dyn Resolve> {
1897        self.resolve_arc_ref().clone()
1898    }
1899    fn resolve_ref(&self) -> &dyn Resolve {
1900        self.resolve_arc_ref().as_ref()
1901    }
1902    fn with_resolve(self, resolve: Arc<dyn Resolve>) -> Self;
1903    /// Get [`Self::Extra`].
1904    fn extra(&self) -> &Self::Extra;
1905    /// Project the `Extra`. Under some circumstances, prevents an extra [`Clone::clone`].
1906    fn map_extra<E: 'static + Clone>(
1907        self,
1908        f: impl FnOnce(&Self::Extra) -> &E,
1909    ) -> Self::WithExtra<E>;
1910    /// Return the old [`Self::Extra`], give a new [`PointInput`] with `E` as `Extra`.
1911    fn replace_extra<E: 'static + Clone>(self, extra: E) -> (Self::Extra, Self::WithExtra<E>);
1912    /// [`Self::replace_extra`] but discarding [`Self::Extra`].
1913    fn with_extra<E: 'static + Clone>(self, extra: E) -> Self::WithExtra<E> {
1914        self.replace_extra(extra).1
1915    }
1916    /// [`ParseInput::parse`] with a different `Extra`.
1917    fn parse_extra<E: 'static + Clone, T: Parse<Self::WithExtra<E>>>(
1918        self,
1919        extra: E,
1920    ) -> crate::Result<T> {
1921        self.with_extra(extra).parse()
1922    }
1923    /// [`ParseInput::parse_inline`] with a different `Extra`.
1924    fn parse_inline_extra<E: 'static + Clone, T: ParseInline<Self::WithExtra<E>>>(
1925        &mut self,
1926        extra: E,
1927    ) -> crate::Result<T>;
1928}
1929
1930impl<T: Sized + IntoIterator> RainbowIterator for T {}
1931
1932/// This can be parsed by consuming the whole rest of the input.
1933///
1934/// Nothing can be parsed after this. It's implementation's responsibility to ensure there are no
1935/// leftover bytes.
1936pub trait Parse<I: ParseInput>: Sized {
1937    /// Parse consuming the whole stream.
1938    fn parse(input: I) -> crate::Result<Self>;
1939}
1940
1941/// This can be parsed from an input, after which we can correctly parse something else.
1942///
1943/// When parsed as the last object, makes sure there are no bytes left in the input (fails if there
1944/// are).
1945pub trait ParseInline<I: ParseInput>: Parse<I> {
1946    /// Parse without consuming the whole stream. Errors on unexpected EOF.
1947    fn parse_inline(input: &mut I) -> crate::Result<Self>;
1948    /// For implementing [`Parse::parse`].
1949    fn parse_as_inline(input: I) -> crate::Result<Self> {
1950        input.parse_as_inline(|input| input.parse_inline())
1951    }
1952    /// Parse a `Vec` of `Self`. Customisable for optimisations.
1953    fn parse_vec(input: I) -> crate::Result<Vec<Self>> {
1954        input.parse_collect()
1955    }
1956    /// Parse a `Vec` of `Self` of length `n`. Customisable for optimisations.
1957    fn parse_vec_n(input: &mut I, n: usize) -> crate::Result<Vec<Self>> {
1958        (0..n).map(|_| input.parse_inline()).collect()
1959    }
1960    /// Parse an array of `Self`. Customisable for optimisations.
1961    fn parse_array<const N: usize>(input: &mut I) -> crate::Result<[Self; N]> {
1962        let mut scratch = std::array::from_fn(|_| None);
1963        for item in scratch.iter_mut() {
1964            *item = Some(input.parse_inline()?);
1965        }
1966        Ok(scratch.map(Option::unwrap))
1967    }
1968    /// Parse a [`GenericArray`] of `Self`. Customisable for optimisations.
1969    fn parse_generic_array<N: ArrayLength>(input: &mut I) -> crate::Result<GenericArray<Self, N>> {
1970        let mut scratch = GenericArray::default();
1971        for item in scratch.iter_mut() {
1972            *item = Some(input.parse_inline()?);
1973        }
1974        Ok(scratch.map(Option::unwrap))
1975    }
1976}
1977
1978/// Implemented if both types have the exact same layout.
1979/// This implies having the same [`MaybeHasNiche::MnArray`].
1980///
1981/// This is represented as two-way conversion for two reasons:
1982/// - to highlight that the conversion is actual equivalence
1983/// - to increase flexibility (mostly to go around the orphan rule)
1984pub trait Equivalent<T>: Sized {
1985    /// Inverse of [`Equivalent::from_equivalent`].
1986    fn into_equivalent(self) -> T;
1987    /// Inverse of [`Equivalent::into_equivalent`].
1988    fn from_equivalent(object: T) -> Self;
1989}
1990
1991pub trait EquivalentFor<U>: Sized {
1992    fn equivalent_for(self) -> U;
1993}
1994
1995impl<T, U: Equivalent<T>> EquivalentFor<U> for T {
1996    fn equivalent_for(self) -> U {
1997        U::from_equivalent(self)
1998    }
1999}
2000
2001pub fn from_equivalent<U>(object: impl EquivalentFor<U>) -> U {
2002    object.equivalent_for()
2003}
2004
2005/// This `Extra` can be used to parse `T` via [`ParseSliceExtra::parse_slice_extra`].
2006pub trait ExtraFor<T> {
2007    /// [`ParseSliceExtra::parse_slice_extra`].
2008    fn parse(&self, data: &[u8], resolve: &Arc<dyn Resolve>) -> Result<T>;
2009
2010    /// [`Self::parse`], then check that [`FullHash::full_hash`] matches.
2011    fn parse_checked(&self, hash: Hash, data: &[u8], resolve: &Arc<dyn Resolve>) -> Result<T>
2012    where
2013        T: FullHash,
2014    {
2015        let object = self.parse(data, resolve)?;
2016        if object.full_hash() != hash {
2017            Err(Error::FullHashMismatch)
2018        } else {
2019            Ok(object)
2020        }
2021    }
2022}
2023
2024impl<T: for<'a> Parse<Input<'a, Extra>>, Extra: Clone> ExtraFor<T> for Extra {
2025    fn parse(&self, data: &[u8], resolve: &Arc<dyn Resolve>) -> Result<T> {
2026        T::parse_slice_extra(data, resolve, self)
2027    }
2028}
2029
2030impl<T> ToOutput for dyn Send + Sync + ExtraFor<T> {
2031    fn to_output(&self, _: &mut (impl ?Sized + Output)) {}
2032}
2033
2034impl<T: Tagged> Tagged for dyn Send + Sync + ExtraFor<T> {
2035    const TAGS: Tags = T::TAGS;
2036    const HASH: Hash = T::HASH;
2037}
2038
2039impl<T> Size for dyn Send + Sync + ExtraFor<T> {
2040    type Size = typenum::U0;
2041    const SIZE: usize = 0;
2042}
2043
2044impl<T> InlineOutput for dyn Send + Sync + ExtraFor<T> {}
2045impl<T> ListHashes for dyn Send + Sync + ExtraFor<T> {}
2046impl<T> Topological for dyn Send + Sync + ExtraFor<T> {}
2047
2048impl<T, I: PointInput<Extra: Send + Sync + ExtraFor<T>>> Parse<I>
2049    for Arc<dyn Send + Sync + ExtraFor<T>>
2050{
2051    fn parse(input: I) -> crate::Result<Self> {
2052        Self::parse_as_inline(input)
2053    }
2054}
2055
2056impl<T, I: PointInput<Extra: Send + Sync + ExtraFor<T>>> ParseInline<I>
2057    for Arc<dyn Send + Sync + ExtraFor<T>>
2058{
2059    fn parse_inline(input: &mut I) -> crate::Result<Self> {
2060        Ok(Arc::new(input.extra().clone()))
2061    }
2062}
2063
2064impl<T> MaybeHasNiche for dyn Send + Sync + ExtraFor<T> {
2065    type MnArray = NoNiche<ZeroNoNiche<<Self as Size>::Size>>;
2066}
2067
2068assert_impl!(
2069    impl<T, E> Inline<E> for Arc<dyn Send + Sync + ExtraFor<T>>
2070    where
2071        T: Object<E>,
2072        E: 'static + Send + Sync + Clone + ExtraFor<T>,
2073    {
2074    }
2075);
2076
2077#[doc(hidden)]
2078pub trait BoundPair: Sized {
2079    type T;
2080    type E;
2081}
2082
2083impl<T, E> BoundPair for (T, E) {
2084    type T = T;
2085    type E = E;
2086}
2087
2088#[test]
2089fn options() {
2090    type T0 = ();
2091    type T1 = Option<T0>;
2092    type T2 = Option<T1>;
2093    type T3 = Option<T2>;
2094    type T4 = Option<T3>;
2095    type T5 = Option<T4>;
2096    assert_eq!(T0::SIZE, 0);
2097    assert_eq!(T1::SIZE, 1);
2098    assert_eq!(T2::SIZE, 1);
2099    assert_eq!(T3::SIZE, 1);
2100    assert_eq!(T4::SIZE, 1);
2101    assert_eq!(T5::SIZE, 1);
2102    assert_eq!(Some(Some(Some(()))).vec(), [0]);
2103    assert_eq!(Some(Some(None::<()>)).vec(), [1]);
2104    assert_eq!(Some(None::<Option<()>>).vec(), [2]);
2105    assert_eq!(None::<Option<Option<()>>>.vec(), [3]);
2106
2107    assert_eq!(false.vec(), [0]);
2108    assert_eq!(true.vec(), [1]);
2109    assert_eq!(Some(false).vec(), [0]);
2110    assert_eq!(Some(true).vec(), [1]);
2111    assert_eq!(None::<bool>.vec(), [2]);
2112    assert_eq!(Some(Some(false)).vec(), [0]);
2113    assert_eq!(Some(Some(true)).vec(), [1]);
2114    assert_eq!(Some(None::<bool>).vec(), [2]);
2115    assert_eq!(None::<Option<bool>>.vec(), [3]);
2116    assert_eq!(Some(Some(Some(false))).vec(), [0]);
2117    assert_eq!(Some(Some(Some(true))).vec(), [1]);
2118    assert_eq!(Some(Some(None::<bool>)).vec(), [2]);
2119    assert_eq!(Some(None::<Option<bool>>).vec(), [3]);
2120    assert_eq!(None::<Option<Option<bool>>>.vec(), [4]);
2121    assert_eq!(Option::<Hash>::SIZE, HASH_SIZE);
2122    assert_eq!(Some(()).vec(), [0]);
2123    assert_eq!(Some(((), ())).vec(), [0]);
2124    assert_eq!(Some(((), true)).vec(), [1]);
2125    assert_eq!(Some((true, true)).vec(), [1, 1]);
2126    assert_eq!(Some((Some(true), true)).vec(), [1, 1]);
2127    assert_eq!(Some((None::<bool>, true)).vec(), [2, 1]);
2128    assert_eq!(Some((true, None::<bool>)).vec(), [1, 2]);
2129    assert_eq!(None::<(Option<bool>, bool)>.vec(), [3, 2]);
2130    assert_eq!(None::<(bool, Option<bool>)>.vec(), [2, 3]);
2131    assert_eq!(Some(Some((Some(true), Some(true)))).vec(), [1, 1],);
2132    assert_eq!(Option::<Hash>::SIZE, HASH_SIZE);
2133    assert_eq!(Option::<Option<Hash>>::SIZE, HASH_SIZE);
2134    assert_eq!(Option::<Option<Option<Hash>>>::SIZE, HASH_SIZE);
2135}
2136
2137pub trait TryDefault: Sized {
2138    fn try_default() -> crate::Result<Self>;
2139}
2140
2141impl<T: Default> TryDefault for T {
2142    fn try_default() -> crate::Result<Self> {
2143        Ok(Self::default())
2144    }
2145}
2146
2147pub trait CanonicalExtra {
2148    type Extra;
2149}
2150
2151pub trait ToCanonicalExtra: CanonicalExtra {
2152    fn canonical_extra(&self) -> Self::Extra;
2153}
2154
2155impl<A: CanonicalExtra, B> CanonicalExtra for (A, B) {
2156    type Extra = A::Extra;
2157}
2158
2159impl<A: ToCanonicalExtra, B> ToCanonicalExtra for (A, B) {
2160    fn canonical_extra(&self) -> Self::Extra {
2161        self.0.canonical_extra()
2162    }
2163}
2164
2165pub trait AsExtra: CanonicalExtra + AsRef<Self::Extra> {
2166    fn as_extra(&self) -> &Self::Extra {
2167        self.as_ref()
2168    }
2169}
2170
2171impl<T: ?Sized + CanonicalExtra + AsRef<T::Extra>> AsExtra for T {}