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