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 without_header;
57pub mod zero_terminated;
58
59pub const HASH_SIZE: usize = sha2_const::Sha256::DIGEST_SIZE;
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ParseAsInline)]
68pub struct Address {
69 pub index: usize,
71 pub hash: Hash,
73}
74
75impl Address {
76 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
103pub type FailFuture<'a, T> = Pin<Box<dyn 'a + Send + Future<Output = Result<T>>>>;
105
106pub type Node<T> = (T, Arc<dyn Resolve>);
107
108pub type ByteNode = Node<Vec<u8>>;
110
111pub trait AsAny {
114 fn any_ref(&self) -> &dyn Any
116 where
117 Self: 'static;
118 fn any_mut(&mut self) -> &mut dyn Any
120 where
121 Self: 'static;
122 fn any_box(self: Box<Self>) -> Box<dyn Any>
124 where
125 Self: 'static;
126 fn any_arc(self: Arc<Self>) -> Arc<dyn Any>
128 where
129 Self: 'static;
130 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
173pub trait Resolve: Send + Sync + AsAny {
175 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
513pub 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
538pub 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 fn reinterpret<T: FromSized<Size = Self::Size>>(&self) -> T {
1053 T::from_sized(&self.to_array())
1054 }
1055}
1056
1057impl<T: Size<Size: ArrayLength> + ToOutput> SizeExt for T {}
1058
1059struct ArrayOutput<'a> {
1060 data: &'a mut [u8],
1061 offset: usize,
1062}
1063
1064impl ArrayOutput<'_> {
1065 fn finalize(self) {
1066 assert_eq!(self.offset, self.data.len());
1067 }
1068}
1069
1070impl Output for ArrayOutput<'_> {
1071 fn write(&mut self, data: &[u8]) {
1072 self.data[self.offset..][..data.len()].copy_from_slice(data);
1073 self.offset += data.len();
1074 }
1075}
1076
1077pub trait FromSized: Size<Size: ArrayLength> {
1078 fn from_sized(data: &GenericArray<u8, Self::Size>) -> Self;
1079}
1080
1081impl<
1082 A: FromSized<Size = An>,
1083 B: FromSized<Size = Bn>,
1084 An,
1085 Bn: Add<An, Output: ArrayLength + Sub<An, Output = Bn>>,
1086> FromSized for (A, B)
1087{
1088 fn from_sized(data: &GenericArray<u8, Self::Size>) -> Self {
1089 let (a, b) = data.split();
1090 (A::from_sized(a), B::from_sized(b))
1091 }
1092}
1093
1094pub trait RainbowIterator: Sized + IntoIterator {
1095 fn iter_to_output(self, output: &mut impl Output)
1096 where
1097 Self::Item: InlineOutput,
1098 {
1099 self.into_iter().for_each(|item| item.to_output(output));
1100 }
1101
1102 fn iter_list_hashes(self, f: &mut impl FnMut(Hash))
1103 where
1104 Self::Item: ListHashes,
1105 {
1106 self.into_iter().for_each(|item| item.list_hashes(f));
1107 }
1108
1109 fn iter_traverse(self, visitor: &mut impl PointVisitor)
1110 where
1111 Self::Item: Topological,
1112 {
1113 self.into_iter().for_each(|item| item.traverse(visitor));
1114 }
1115}
1116
1117pub trait ParseInput: Sized {
1118 type Data: AsRef<[u8]> + Deref<Target = [u8]> + Into<Vec<u8>> + Copy;
1119 fn parse_chunk<'a, const N: usize>(&mut self) -> crate::Result<&'a [u8; N]>
1120 where
1121 Self: 'a;
1122 fn parse_n(&mut self, n: usize) -> crate::Result<Self::Data>;
1123 fn parse_until_zero(&mut self) -> crate::Result<Self::Data>;
1124 fn parse_n_compare(&mut self, n: usize, c: &[u8]) -> crate::Result<Option<Self::Data>> {
1125 let data = self.parse_n(n)?;
1126 if *data == *c {
1127 Ok(None)
1128 } else {
1129 Ok(Some(data))
1130 }
1131 }
1132 fn reparse<T: Parse<Self>>(&mut self, data: Self::Data) -> crate::Result<T>;
1133 fn parse_ahead<T: Parse<Self>>(&mut self, n: usize) -> crate::Result<T> {
1134 let data = self.parse_n(n)?;
1135 self.reparse(data)
1136 }
1137 fn parse_zero_terminated<T: Parse<Self>>(&mut self) -> crate::Result<T> {
1138 let data = self.parse_until_zero()?;
1139 self.reparse(data)
1140 }
1141 fn parse_compare<T: Parse<Self>>(&mut self, n: usize, c: &[u8]) -> Result<Option<T>> {
1142 self.parse_n_compare(n, c)?
1143 .map(|data| self.reparse(data))
1144 .transpose()
1145 }
1146 fn parse_all(self) -> crate::Result<Self::Data>;
1147 fn empty(self) -> crate::Result<()>;
1148 fn non_empty(self) -> crate::Result<Option<Self>>;
1149
1150 fn consume(self, f: impl FnMut(&mut Self) -> crate::Result<()>) -> crate::Result<()> {
1151 self.collect(f)
1152 }
1153
1154 fn parse_collect<T: ParseInline<Self>, B: FromIterator<T>>(self) -> crate::Result<B> {
1155 self.collect(|input| input.parse_inline())
1156 }
1157
1158 fn collect<T, B: FromIterator<T>>(
1159 self,
1160 f: impl FnMut(&mut Self) -> crate::Result<T>,
1161 ) -> crate::Result<B> {
1162 self.iter(f).collect()
1163 }
1164
1165 fn iter<T>(
1166 self,
1167 mut f: impl FnMut(&mut Self) -> crate::Result<T>,
1168 ) -> impl Iterator<Item = crate::Result<T>> {
1169 let mut state = Some(self);
1170 std::iter::from_fn(move || {
1171 let mut input = match state.take()?.non_empty() {
1172 Ok(input) => input?,
1173 Err(e) => return Some(Err(e)),
1174 };
1175 let item = f(&mut input);
1176 state = Some(input);
1177 Some(item)
1178 })
1179 }
1180
1181 fn parse_inline<T: ParseInline<Self>>(&mut self) -> crate::Result<T> {
1182 T::parse_inline(self)
1183 }
1184
1185 fn parse<T: Parse<Self>>(self) -> crate::Result<T> {
1186 T::parse(self)
1187 }
1188
1189 fn parse_vec<T: ParseInline<Self>>(self) -> crate::Result<Vec<T>> {
1190 T::parse_vec(self)
1191 }
1192
1193 fn parse_vec_n<T: ParseInline<Self>>(&mut self, n: usize) -> crate::Result<Vec<T>> {
1194 T::parse_vec_n(self, n)
1195 }
1196
1197 fn parse_array<T: ParseInline<Self>, const N: usize>(&mut self) -> crate::Result<[T; N]> {
1198 T::parse_array(self)
1199 }
1200
1201 fn parse_generic_array<T: ParseInline<Self>, N: ArrayLength>(
1202 &mut self,
1203 ) -> crate::Result<GenericArray<T, N>> {
1204 T::parse_generic_array(self)
1205 }
1206}
1207
1208pub trait PointInput: ParseInput {
1209 type Extra: 'static + Clone;
1210 type WithExtra<E: 'static + Clone>: PointInput<Extra = E, WithExtra<Self::Extra> = Self>;
1211 fn next_index(&mut self) -> usize;
1212 fn resolve_arc_ref(&self) -> &Arc<dyn Resolve>;
1213 fn resolve(&self) -> Arc<dyn Resolve> {
1214 self.resolve_arc_ref().clone()
1215 }
1216 fn resolve_ref(&self) -> &dyn Resolve {
1217 self.resolve_arc_ref().as_ref()
1218 }
1219 fn extra(&self) -> &Self::Extra;
1221 fn map_extra<E: 'static + Clone>(
1223 self,
1224 f: impl FnOnce(&Self::Extra) -> &E,
1225 ) -> Self::WithExtra<E>;
1226 fn replace_extra<E: 'static + Clone>(self, extra: E) -> (Self::Extra, Self::WithExtra<E>);
1228 fn with_extra<E: 'static + Clone>(self, extra: E) -> Self::WithExtra<E> {
1230 self.replace_extra(extra).1
1231 }
1232 fn parse_extra<E: 'static + Clone, T: Parse<Self::WithExtra<E>>>(
1234 self,
1235 extra: E,
1236 ) -> crate::Result<T> {
1237 self.with_extra(extra).parse()
1238 }
1239 fn parse_inline_extra<E: 'static + Clone, T: ParseInline<Self::WithExtra<E>>>(
1241 &mut self,
1242 extra: E,
1243 ) -> crate::Result<T>;
1244}
1245
1246impl<T: Sized + IntoIterator> RainbowIterator for T {}
1247
1248pub trait Parse<I: ParseInput>: Sized {
1253 fn parse(input: I) -> crate::Result<Self>;
1255}
1256
1257pub trait ParseInline<I: ParseInput>: Parse<I> {
1262 fn parse_inline(input: &mut I) -> crate::Result<Self>;
1264 fn parse_as_inline(mut input: I) -> crate::Result<Self> {
1266 let object = Self::parse_inline(&mut input)?;
1267 input.empty()?;
1268 Ok(object)
1269 }
1270 fn parse_vec(input: I) -> crate::Result<Vec<Self>> {
1272 input.parse_collect()
1273 }
1274 fn parse_vec_n(input: &mut I, n: usize) -> crate::Result<Vec<Self>> {
1276 (0..n).map(|_| input.parse_inline()).collect()
1277 }
1278 fn parse_array<const N: usize>(input: &mut I) -> crate::Result<[Self; N]> {
1280 let mut scratch = std::array::from_fn(|_| None);
1281 for item in scratch.iter_mut() {
1282 *item = Some(input.parse_inline()?);
1283 }
1284 Ok(scratch.map(Option::unwrap))
1285 }
1286 fn parse_generic_array<N: ArrayLength>(input: &mut I) -> crate::Result<GenericArray<Self, N>> {
1288 let mut scratch = GenericArray::default();
1289 for item in scratch.iter_mut() {
1290 *item = Some(input.parse_inline()?);
1291 }
1292 Ok(scratch.map(Option::unwrap))
1293 }
1294}
1295
1296pub trait Equivalent<T>: Sized {
1303 fn into_equivalent(self) -> T;
1305 fn from_equivalent(object: T) -> Self;
1307}
1308
1309pub trait ExtraFor<T> {
1311 fn parse(&self, data: &[u8], resolve: &Arc<dyn Resolve>) -> Result<T>;
1313
1314 fn parse_checked(&self, hash: Hash, data: &[u8], resolve: &Arc<dyn Resolve>) -> Result<T>
1316 where
1317 T: FullHash,
1318 {
1319 let object = self.parse(data, resolve)?;
1320 if object.full_hash() != hash {
1321 Err(Error::FullHashMismatch)
1322 } else {
1323 Ok(object)
1324 }
1325 }
1326}
1327
1328impl<T: for<'a> Parse<Input<'a, Extra>>, Extra: Clone> ExtraFor<T> for Extra {
1329 fn parse(&self, data: &[u8], resolve: &Arc<dyn Resolve>) -> Result<T> {
1330 T::parse_slice_extra(data, resolve, self)
1331 }
1332}
1333
1334impl<T> ToOutput for dyn Send + Sync + ExtraFor<T> {
1335 fn to_output(&self, _: &mut impl Output) {}
1336}
1337
1338impl<T: Tagged> Tagged for dyn Send + Sync + ExtraFor<T> {
1339 const TAGS: Tags = T::TAGS;
1340 const HASH: Hash = T::HASH;
1341}
1342
1343impl<T> Size for dyn Send + Sync + ExtraFor<T> {
1344 type Size = typenum::U0;
1345 const SIZE: usize = 0;
1346}
1347
1348impl<T> InlineOutput for dyn Send + Sync + ExtraFor<T> {}
1349impl<T> ListHashes for dyn Send + Sync + ExtraFor<T> {}
1350impl<T> Topological for dyn Send + Sync + ExtraFor<T> {}
1351
1352impl<T, I: PointInput<Extra: Send + Sync + ExtraFor<T>>> Parse<I>
1353 for Arc<dyn Send + Sync + ExtraFor<T>>
1354{
1355 fn parse(input: I) -> crate::Result<Self> {
1356 Self::parse_as_inline(input)
1357 }
1358}
1359
1360impl<T, I: PointInput<Extra: Send + Sync + ExtraFor<T>>> ParseInline<I>
1361 for Arc<dyn Send + Sync + ExtraFor<T>>
1362{
1363 fn parse_inline(input: &mut I) -> crate::Result<Self> {
1364 Ok(Arc::new(input.extra().clone()))
1365 }
1366}
1367
1368impl<T> MaybeHasNiche for dyn Send + Sync + ExtraFor<T> {
1369 type MnArray = NoNiche<ZeroNoNiche<<Self as Size>::Size>>;
1370}
1371
1372assert_impl!(
1373 impl<T, E> Inline<E> for Arc<dyn Send + Sync + ExtraFor<T>>
1374 where
1375 T: Object<E>,
1376 E: 'static + Send + Sync + Clone + ExtraFor<T>,
1377 {
1378 }
1379);
1380
1381#[doc(hidden)]
1382pub trait BoundPair: Sized {
1383 type T;
1384 type E;
1385}
1386
1387impl<T, E> BoundPair for (T, E) {
1388 type T = T;
1389 type E = E;
1390}
1391
1392#[test]
1393fn options() {
1394 type T0 = ();
1395 type T1 = Option<T0>;
1396 type T2 = Option<T1>;
1397 type T3 = Option<T2>;
1398 type T4 = Option<T3>;
1399 type T5 = Option<T4>;
1400 assert_eq!(T0::SIZE, 0);
1401 assert_eq!(T1::SIZE, 1);
1402 assert_eq!(T2::SIZE, 1);
1403 assert_eq!(T3::SIZE, 1);
1404 assert_eq!(T4::SIZE, 1);
1405 assert_eq!(T5::SIZE, 1);
1406 assert_eq!(Some(Some(Some(()))).vec(), [0]);
1407 assert_eq!(Some(Some(None::<()>)).vec(), [1]);
1408 assert_eq!(Some(None::<Option<()>>).vec(), [2]);
1409 assert_eq!(None::<Option<Option<()>>>.vec(), [3]);
1410
1411 assert_eq!(false.vec(), [0]);
1412 assert_eq!(true.vec(), [1]);
1413 assert_eq!(Some(false).vec(), [0]);
1414 assert_eq!(Some(true).vec(), [1]);
1415 assert_eq!(None::<bool>.vec(), [2]);
1416 assert_eq!(Some(Some(false)).vec(), [0]);
1417 assert_eq!(Some(Some(true)).vec(), [1]);
1418 assert_eq!(Some(None::<bool>).vec(), [2]);
1419 assert_eq!(None::<Option<bool>>.vec(), [3]);
1420 assert_eq!(Some(Some(Some(false))).vec(), [0]);
1421 assert_eq!(Some(Some(Some(true))).vec(), [1]);
1422 assert_eq!(Some(Some(None::<bool>)).vec(), [2]);
1423 assert_eq!(Some(None::<Option<bool>>).vec(), [3]);
1424 assert_eq!(None::<Option<Option<bool>>>.vec(), [4]);
1425 assert_eq!(Option::<Hash>::SIZE, HASH_SIZE);
1426 assert_eq!(Some(()).vec(), [0]);
1427 assert_eq!(Some(((), ())).vec(), [0]);
1428 assert_eq!(Some(((), true)).vec(), [1]);
1429 assert_eq!(Some((true, true)).vec(), [1, 1]);
1430 assert_eq!(Some((Some(true), true)).vec(), [1, 1]);
1431 assert_eq!(Some((None::<bool>, true)).vec(), [2, 1]);
1432 assert_eq!(Some((true, None::<bool>)).vec(), [1, 2]);
1433 assert_eq!(None::<(Option<bool>, bool)>.vec(), [3, 2]);
1434 assert_eq!(None::<(bool, Option<bool>)>.vec(), [2, 3]);
1435 assert_eq!(Some(Some((Some(true), Some(true)))).vec(), [1, 1],);
1436 assert_eq!(Option::<Hash>::SIZE, HASH_SIZE);
1437 assert_eq!(Option::<Option<Hash>>::SIZE, HASH_SIZE);
1438 assert_eq!(Option::<Option<Option<Hash>>>::SIZE, HASH_SIZE);
1439}