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