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