1extern crate self as object_rainbow;
2
3use std::{
4 any::{Any, TypeId},
5 cell::Cell,
6 convert::Infallible,
7 future::ready,
8 marker::PhantomData,
9 ops::{Deref, DerefMut},
10 pin::Pin,
11 sync::Arc,
12};
13
14pub use anyhow::anyhow;
15use futures_util::TryFutureExt;
16use generic_array::{ArrayLength, GenericArray};
17pub use object_rainbow_derive::{
18 Enum, Inline, MaybeHasNiche, Object, Parse, ParseAsInline, ParseInline, ReflessInline,
19 ReflessObject, Size, Tagged, ToOutput, Topological,
20};
21use sha2::{Digest, Sha256};
22#[doc(hidden)]
23pub use typenum;
24use typenum::Unsigned;
25
26pub use self::enumkind::Enum;
27pub use self::hash::{Hash, OptionalHash};
28pub use self::niche::{
29 AutoEnumNiche, AutoNiche, HackNiche, MaybeHasNiche, Niche, NicheForUnsized, NoNiche, OneNiche,
30 SomeNiche, ZeroNiche, ZeroNoNiche,
31};
32#[doc(hidden)]
33pub use self::niche::{MaybeNiche, MnArray, NicheFoldOrArray, NicheOr};
34
35pub mod enumkind;
36mod hash;
37pub mod hashed;
38mod impls;
39pub mod length_prefixed;
40mod niche;
41pub mod numeric;
42#[cfg(feature = "serde")]
43mod point_deserialize;
44mod sha2_const;
45
46#[macro_export]
47macro_rules! error_parse {
49 ($($t:tt)*) => {
50 $crate::Error::Parse($crate::anyhow!($($t)*))
51 };
52}
53
54#[macro_export]
55macro_rules! error_fetch {
57 ($($t:tt)*) => {
58 $crate::Error::Fetch($crate::anyhow!($($t)*))
59 };
60}
61
62#[derive(Debug, thiserror::Error)]
64#[non_exhaustive]
65pub enum Error {
66 #[error(transparent)]
68 Parse(anyhow::Error),
69 #[error(transparent)]
71 Fetch(anyhow::Error),
72 #[error("extra input left")]
74 ExtraInputLeft,
75 #[error("end of input")]
77 EndOfInput,
78 #[error("address index out of bounds")]
80 AddressOutOfBounds,
81 #[error("hash resolution mismatch")]
83 ResolutionMismatch,
84 #[error("data hash mismatch")]
86 DataMismatch,
87 #[error("discriminant overflow")]
89 DiscriminantOverflow,
90 #[error("zero")]
92 Zero,
93 #[error("out of bounds")]
95 OutOfBounds,
96 #[error("length out of bounds")]
98 UnsupportedLength,
99 #[error(transparent)]
101 Utf8(std::string::FromUtf8Error),
102 #[error("unknown extension")]
104 UnknownExtension,
105 #[error("wrong extension type")]
107 ExtensionType,
108}
109
110impl Error {
111 pub fn parse(e: impl Into<anyhow::Error>) -> Self {
113 Self::Parse(e.into())
114 }
115
116 pub fn fetch(e: impl Into<anyhow::Error>) -> Self {
118 Self::Fetch(e.into())
119 }
120}
121
122pub type Result<T> = std::result::Result<T, Error>;
123
124pub const HASH_SIZE: usize = sha2_const::Sha256::DIGEST_SIZE;
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ParseAsInline)]
133pub struct Address {
134 pub index: usize,
136 pub hash: Hash,
138}
139
140impl Address {
141 pub fn from_hash(hash: Hash) -> Self {
144 Self {
145 index: usize::MAX,
146 hash,
147 }
148 }
149}
150
151impl<I: PointInput> ParseInline<I> for Address {
152 fn parse_inline(input: &mut I) -> crate::Result<Self> {
153 Ok(Self {
154 index: input.next_index(),
155 hash: input.parse_inline()?,
156 })
157 }
158}
159
160pub type FailFuture<'a, T> = Pin<Box<dyn 'a + Send + Future<Output = Result<T>>>>;
162
163pub type ByteNode = (Vec<u8>, Arc<dyn Resolve>);
165
166trait FromInner {
167 type Inner: 'static + Clone;
168 type Extra: 'static + Clone;
169
170 fn from_inner(inner: Self::Inner, extra: Self::Extra) -> Self;
171}
172
173pub trait AsAny {
176 fn any_ref(&self) -> &dyn Any
178 where
179 Self: 'static;
180 fn any_mut(&mut self) -> &mut dyn Any
182 where
183 Self: 'static;
184 fn any_box(self: Box<Self>) -> Box<dyn Any>
186 where
187 Self: 'static;
188 fn any_arc(self: Arc<Self>) -> Arc<dyn Any>
190 where
191 Self: 'static;
192 fn any_arc_sync(self: Arc<Self>) -> Arc<dyn Send + Sync + Any>
194 where
195 Self: 'static + Send + Sync;
196}
197
198impl<T> AsAny for T {
199 fn any_ref(&self) -> &dyn Any
200 where
201 Self: 'static,
202 {
203 self
204 }
205
206 fn any_mut(&mut self) -> &mut dyn Any
207 where
208 Self: 'static,
209 {
210 self
211 }
212
213 fn any_box(self: Box<Self>) -> Box<dyn Any>
214 where
215 Self: 'static,
216 {
217 self
218 }
219
220 fn any_arc(self: Arc<Self>) -> Arc<dyn Any>
221 where
222 Self: 'static,
223 {
224 self
225 }
226
227 fn any_arc_sync(self: Arc<Self>) -> Arc<dyn Send + Sync + Any>
228 where
229 Self: 'static + Send + Sync,
230 {
231 self
232 }
233}
234
235pub trait Resolve: Send + Sync + AsAny {
237 fn resolve(&'_ self, address: Address) -> FailFuture<'_, ByteNode>;
239 fn resolve_data(&'_ self, address: Address) -> FailFuture<'_, Vec<u8>>;
240 fn resolve_extension(&self, address: Address, typeid: TypeId) -> crate::Result<&dyn Any> {
242 let _ = address;
243 let _ = typeid;
244 Err(Error::UnknownExtension)
245 }
246 fn extension(&self, typeid: TypeId) -> crate::Result<&dyn Any> {
248 let _ = typeid;
249 Err(Error::UnknownExtension)
250 }
251 fn name(&self) -> &str;
253}
254
255pub trait FetchBytes: AsAny {
256 fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode>;
257 fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>>;
258 fn as_inner(&self) -> Option<&dyn Any> {
259 None
260 }
261}
262
263pub trait Fetch: Send + Sync + FetchBytes {
264 type T;
265 fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)>;
266 fn fetch(&'_ self) -> FailFuture<'_, Self::T>;
267 fn get(&self) -> Option<&Self::T> {
268 None
269 }
270 fn get_mut(&mut self) -> Option<&mut Self::T> {
271 None
272 }
273 fn get_mut_finalize(&mut self) {}
274}
275
276trait FetchBytesExt: FetchBytes {
277 fn inner_cast<T: FromInner>(&self, extra: &T::Extra) -> Option<T> {
278 self.as_inner()?
279 .downcast_ref()
280 .cloned()
281 .map(|inner| T::from_inner(inner, extra.clone()))
282 }
283}
284
285impl<T: ?Sized + FetchBytes> FetchBytesExt for T {}
286
287#[derive(Clone, ParseAsInline)]
288pub struct RawPointInner {
289 hash: Hash,
290 origin: Arc<dyn Send + Sync + FetchBytes>,
291}
292
293impl RawPointInner {
294 pub fn cast<T, Extra: 'static + Clone>(self, extra: Extra) -> RawPoint<T, Extra> {
295 RawPoint::from_inner(self, extra)
296 }
297}
298
299impl RawPointInner {
300 pub fn from_address(address: Address, resolve: Arc<dyn Resolve>) -> Self {
301 Self {
302 hash: address.hash,
303 origin: Arc::new(ByAddressInner { address, resolve }),
304 }
305 }
306}
307
308impl ToOutput for RawPointInner {
309 fn to_output(&self, output: &mut dyn Output) {
310 self.hash.to_output(output);
311 }
312}
313
314impl<I: PointInput> ParseInline<I> for RawPointInner {
315 fn parse_inline(input: &mut I) -> crate::Result<Self> {
316 Ok(Self::from_address(input.parse_inline()?, input.resolve()))
317 }
318}
319
320impl Tagged for RawPointInner {}
321
322impl Singular for RawPointInner {
323 fn hash(&self) -> Hash {
324 self.hash
325 }
326}
327
328impl<T, Extra: 'static + Send + Sync> Singular for RawPoint<T, Extra> {
329 fn hash(&self) -> Hash {
330 self.inner.hash()
331 }
332}
333
334#[derive(ToOutput, Topological, Parse, ParseInline)]
335pub struct ObjectMarker<T: ?Sized> {
336 object: PhantomData<fn() -> T>,
337}
338
339impl<T: ?Sized> Clone for ObjectMarker<T> {
340 fn clone(&self) -> Self {
341 *self
342 }
343}
344
345impl<T: ?Sized> Copy for ObjectMarker<T> {}
346
347impl<T: ?Sized> Default for ObjectMarker<T> {
348 fn default() -> Self {
349 Self {
350 object: Default::default(),
351 }
352 }
353}
354
355impl<T: ?Sized + Tagged> Tagged for ObjectMarker<T> {}
356impl<T: ?Sized + 'static + Tagged, Extra: 'static> Object<Extra> for ObjectMarker<T> {}
357impl<T: ?Sized + 'static + Tagged, Extra: 'static> Inline<Extra> for ObjectMarker<T> {}
358
359#[derive(Clone, ParseAsInline)]
360struct Extras<Extra>(Extra);
361
362impl<Extra> Deref for Extras<Extra> {
363 type Target = Extra;
364
365 fn deref(&self) -> &Self::Target {
366 &self.0
367 }
368}
369
370impl<Extra> ToOutput for Extras<Extra> {
371 fn to_output(&self, _: &mut dyn Output) {}
372}
373
374impl<I: PointInput> ParseInline<I> for Extras<I::Extra> {
375 fn parse_inline(input: &mut I) -> crate::Result<Self> {
376 Ok(Self(input.extra().clone()))
377 }
378}
379
380impl<Extra> Tagged for Extras<Extra> {}
381impl<Extra> Topological for Extras<Extra> {}
382impl<Extra: 'static + Send + Sync + Clone> Object<Extra> for Extras<Extra> {}
383impl<Extra: 'static + Send + Sync + Clone> Inline<Extra> for Extras<Extra> {}
384
385#[derive(ToOutput, Tagged, Parse, ParseInline)]
386pub struct RawPoint<T = Infallible, Extra = ()> {
387 inner: RawPointInner,
388 extra: Extras<Extra>,
389 object: ObjectMarker<T>,
390}
391
392impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Topological for RawPoint<T, Extra> {
393 fn accept_points(&self, visitor: &mut impl PointVisitor) {
394 visitor.visit(&self.clone().point());
395 }
396
397 fn point_count(&self) -> usize {
398 1
399 }
400}
401
402impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Object<Extra> for RawPoint<T, Extra> {}
403impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Inline<Extra> for RawPoint<T, Extra> {}
404
405impl<T, Extra: 'static + Clone> FromInner for RawPoint<T, Extra> {
406 type Inner = RawPointInner;
407 type Extra = Extra;
408
409 fn from_inner(inner: Self::Inner, extra: Self::Extra) -> Self {
410 RawPoint {
411 inner,
412 extra: Extras(extra),
413 object: Default::default(),
414 }
415 }
416}
417
418impl<T, Extra: Clone> Clone for RawPoint<T, Extra> {
419 fn clone(&self) -> Self {
420 Self {
421 inner: self.inner.clone(),
422 extra: self.extra.clone(),
423 object: Default::default(),
424 }
425 }
426}
427
428impl<T> Point<T> {
429 pub fn raw<Extra: 'static + Clone>(self, extra: Extra) -> RawPoint<T, Extra> {
430 {
431 if let Some(raw) = self.origin.inner_cast(&extra) {
432 return raw;
433 }
434 }
435 RawPointInner {
436 hash: self.hash.unwrap(),
437 origin: self.origin,
438 }
439 .cast(extra)
440 }
441}
442
443impl<T, Extra: 'static + Clone> RawPoint<T, Extra> {
444 pub fn cast<U>(self) -> RawPoint<U, Extra> {
445 self.inner.cast(self.extra.0)
446 }
447}
448
449impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> RawPoint<T, Extra> {
450 pub fn point(self) -> Point<T> {
451 Point::from_origin(self.inner.hash, Arc::new(self))
452 }
453}
454
455impl FetchBytes for RawPointInner {
456 fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
457 self.origin.fetch_bytes()
458 }
459
460 fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
461 self.origin.fetch_data()
462 }
463}
464
465impl<T, Extra: 'static> FetchBytes for RawPoint<T, Extra> {
466 fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
467 self.inner.fetch_bytes()
468 }
469
470 fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
471 self.inner.fetch_data()
472 }
473
474 fn as_inner(&self) -> Option<&dyn Any> {
475 Some(&self.inner)
476 }
477}
478
479impl<T: Object<Extra>, Extra: 'static + Send + Sync> Fetch for RawPoint<T, Extra> {
480 type T = T;
481
482 fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
483 Box::pin(async {
484 let (data, resolve) = self.inner.origin.fetch_bytes().await?;
485 let object = T::parse_slice_extra(&data, &resolve, &self.extra)?;
486 if self.inner.hash != object.full_hash() {
487 Err(Error::DataMismatch)
488 } else {
489 Ok((object, resolve))
490 }
491 })
492 }
493
494 fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
495 Box::pin(async {
496 let (data, resolve) = self.inner.origin.fetch_bytes().await?;
497 let object = T::parse_slice_extra(&data, &resolve, &self.extra)?;
498 if self.inner.hash != object.full_hash() {
499 Err(Error::DataMismatch)
500 } else {
501 Ok(object)
502 }
503 })
504 }
505}
506
507impl<T> Point<T> {
508 pub fn extract_resolve<R: Any>(&self) -> Option<(&Address, &R)> {
509 let ByAddressInner { address, resolve } =
510 self.origin.as_inner()?.downcast_ref::<ByAddressInner>()?;
511 let resolve = resolve.as_ref().any_ref().downcast_ref::<R>()?;
512 Some((address, resolve))
513 }
514}
515
516#[derive(ParseAsInline)]
517#[must_use]
518pub struct Point<T> {
519 hash: OptionalHash,
520 origin: Arc<dyn Fetch<T = T>>,
521}
522
523impl<T> PartialOrd for Point<T> {
524 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
525 Some(self.cmp(other))
526 }
527}
528
529impl<T> Ord for Point<T> {
530 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
531 self.hash().cmp(&other.hash())
532 }
533}
534
535impl<T> Eq for Point<T> {}
536
537impl<T> PartialEq for Point<T> {
538 fn eq(&self, other: &Self) -> bool {
539 self.hash() == other.hash()
540 }
541}
542
543impl<T> Clone for Point<T> {
544 fn clone(&self) -> Self {
545 Self {
546 hash: self.hash,
547 origin: self.origin.clone(),
548 }
549 }
550}
551
552impl<T> Point<T> {
553 pub fn from_origin(hash: Hash, origin: Arc<dyn Fetch<T = T>>) -> Self {
554 Self {
555 hash: hash.into(),
556 origin,
557 }
558 }
559
560 fn map_origin<U>(
561 self,
562 f: impl FnOnce(Arc<dyn Fetch<T = T>>) -> Arc<dyn Fetch<T = U>>,
563 ) -> Point<U> {
564 Point {
565 hash: self.hash,
566 origin: f(self.origin),
567 }
568 }
569}
570
571impl<T> Size for Point<T> {
572 const SIZE: usize = HASH_SIZE;
573 type Size = typenum::generic_const_mappings::U<HASH_SIZE>;
574}
575
576impl<T: Object> Point<T> {
577 pub fn from_address(address: Address, resolve: Arc<dyn Resolve>) -> Self {
578 Self::from_address_extra(address, resolve, ())
579 }
580}
581
582impl<T> Point<T> {
583 pub fn from_address_extra<Extra: 'static + Send + Sync + Clone>(
584 address: Address,
585 resolve: Arc<dyn Resolve>,
586 extra: Extra,
587 ) -> Self
588 where
589 T: Object<Extra>,
590 {
591 Self::from_origin(
592 address.hash,
593 Arc::new(ByAddress::from_inner(
594 ByAddressInner { address, resolve },
595 extra,
596 )),
597 )
598 }
599
600 pub fn with_resolve<Extra: 'static + Send + Sync + Clone>(
601 &self,
602 resolve: Arc<dyn Resolve>,
603 extra: Extra,
604 ) -> Self
605 where
606 T: Object<Extra>,
607 {
608 Self::from_address_extra(Address::from_hash(self.hash()), resolve, extra)
609 }
610}
611
612#[derive(Clone)]
613struct ByAddressInner {
614 address: Address,
615 resolve: Arc<dyn Resolve>,
616}
617
618impl FetchBytes for ByAddressInner {
619 fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
620 self.resolve.resolve(self.address)
621 }
622
623 fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
624 self.resolve.resolve_data(self.address)
625 }
626}
627
628struct ByAddress<T, Extra> {
629 inner: ByAddressInner,
630 extra: Extra,
631 _object: PhantomData<fn() -> T>,
632}
633
634impl<T, Extra: 'static + Clone> ByAddress<T, Extra> {
635 fn from_inner(inner: ByAddressInner, extra: Extra) -> Self {
636 Self {
637 inner,
638 extra,
639 _object: PhantomData,
640 }
641 }
642}
643
644impl<T, Extra: 'static> FetchBytes for ByAddress<T, Extra> {
645 fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
646 self.inner.fetch_bytes()
647 }
648
649 fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
650 self.inner.fetch_data()
651 }
652
653 fn as_inner(&self) -> Option<&dyn Any> {
654 Some(&self.inner)
655 }
656}
657
658impl<T: Object<Extra>, Extra: 'static + Send + Sync> Fetch for ByAddress<T, Extra> {
659 type T = T;
660
661 fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
662 Box::pin(async {
663 let (data, resolve) = self.fetch_bytes().await?;
664 let object = T::parse_slice_extra(&data, &resolve, &self.extra)?;
665 if self.inner.address.hash != object.full_hash() {
666 Err(Error::DataMismatch)
667 } else {
668 Ok((object, resolve))
669 }
670 })
671 }
672
673 fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
674 Box::pin(async {
675 let (data, resolve) = self.fetch_bytes().await?;
676 let object = T::parse_slice_extra(&data, &resolve, &self.extra)?;
677 if self.inner.address.hash != object.full_hash() {
678 Err(Error::DataMismatch)
679 } else {
680 Ok(object)
681 }
682 })
683 }
684}
685
686pub trait PointVisitor {
687 fn visit<T: Traversible>(&mut self, point: &Point<T>);
688}
689
690struct HashVisitor<F>(F);
691
692impl<F: FnMut(Hash)> PointVisitor for HashVisitor<F> {
693 fn visit<T: Traversible>(&mut self, point: &Point<T>) {
694 self.0(point.hash());
695 }
696}
697
698pub struct ReflessInput<'a> {
699 data: Option<&'a [u8]>,
700}
701
702pub struct Input<'a, Extra = ()> {
703 refless: ReflessInput<'a>,
704 resolve: &'a Arc<dyn Resolve>,
705 index: &'a Cell<usize>,
706 extra: &'a Extra,
707}
708
709impl<'a, Extra> Deref for Input<'a, Extra> {
710 type Target = ReflessInput<'a>;
711
712 fn deref(&self) -> &Self::Target {
713 &self.refless
714 }
715}
716
717impl<Extra> DerefMut for Input<'_, Extra> {
718 fn deref_mut(&mut self) -> &mut Self::Target {
719 &mut self.refless
720 }
721}
722
723impl<'a, Extra> Input<'a, Extra> {
724 pub fn replace_extra<E>(self, extra: &'a E) -> Input<'a, E> {
725 Input {
726 refless: self.refless,
727 resolve: self.resolve,
728 index: self.index,
729 extra,
730 }
731 }
732}
733
734impl<'a> ReflessInput<'a> {
735 fn data(&self) -> crate::Result<&'a [u8]> {
736 self.data.ok_or(Error::EndOfInput)
737 }
738
739 fn make_error<T>(&mut self, e: crate::Error) -> crate::Result<T> {
740 self.data = None;
741 Err(e)
742 }
743
744 fn end_of_input<T>(&mut self) -> crate::Result<T> {
745 self.make_error(Error::EndOfInput)
746 }
747}
748
749impl ParseInput for ReflessInput<'_> {
750 fn parse_chunk<'a, const N: usize>(&mut self) -> crate::Result<&'a [u8; N]>
751 where
752 Self: 'a,
753 {
754 match self.data()?.split_first_chunk() {
755 Some((chunk, data)) => {
756 self.data = Some(data);
757 Ok(chunk)
758 }
759 None => self.end_of_input(),
760 }
761 }
762
763 fn parse_n<'a>(&mut self, n: usize) -> crate::Result<&'a [u8]>
764 where
765 Self: 'a,
766 {
767 match self.data()?.split_at_checked(n) {
768 Some((chunk, data)) => {
769 self.data = Some(data);
770 Ok(chunk)
771 }
772 None => self.end_of_input(),
773 }
774 }
775
776 fn parse_ahead<T: Parse<Self>>(&mut self, n: usize) -> crate::Result<T> {
777 let input = ReflessInput {
778 data: Some(self.parse_n(n)?),
779 };
780 T::parse(input)
781 }
782
783 fn parse_compare<T: ParseInline<Self>>(&mut self, n: usize, c: &[u8]) -> Result<Option<T>> {
784 match self.data()?.split_at_checked(n) {
785 Some((chunk, data)) => {
786 if chunk == c {
787 self.data = Some(data);
788 Ok(None)
789 } else {
790 self.parse_inline().map(Some)
791 }
792 }
793 None => self.end_of_input(),
794 }
795 }
796
797 fn parse_all<'a>(self) -> crate::Result<&'a [u8]>
798 where
799 Self: 'a,
800 {
801 self.data()
802 }
803
804 fn empty(self) -> crate::Result<()> {
805 if self.data()?.is_empty() {
806 Ok(())
807 } else {
808 Err(Error::ExtraInputLeft)
809 }
810 }
811
812 fn non_empty(self) -> crate::Result<Option<Self>> {
813 Ok(if self.data()?.is_empty() {
814 None
815 } else {
816 Some(self)
817 })
818 }
819}
820
821impl<Extra> ParseInput for Input<'_, Extra> {
822 fn parse_chunk<'a, const N: usize>(&mut self) -> crate::Result<&'a [u8; N]>
823 where
824 Self: 'a,
825 {
826 (**self).parse_chunk()
827 }
828
829 fn parse_n<'a>(&mut self, n: usize) -> crate::Result<&'a [u8]>
830 where
831 Self: 'a,
832 {
833 (**self).parse_n(n)
834 }
835
836 fn parse_ahead<T: Parse<Self>>(&mut self, n: usize) -> crate::Result<T> {
837 let input = Input {
838 refless: ReflessInput {
839 data: Some(self.parse_n(n)?),
840 },
841 resolve: self.resolve,
842 index: self.index,
843 extra: self.extra,
844 };
845 T::parse(input)
846 }
847
848 fn parse_compare<T: ParseInline<Self>>(&mut self, n: usize, c: &[u8]) -> Result<Option<T>> {
849 match self.data()?.split_at_checked(n) {
850 Some((chunk, data)) => {
851 if chunk == c {
852 self.data = Some(data);
853 Ok(None)
854 } else {
855 self.parse_inline().map(Some)
856 }
857 }
858 None => self.end_of_input(),
859 }
860 }
861
862 fn parse_all<'a>(self) -> crate::Result<&'a [u8]>
863 where
864 Self: 'a,
865 {
866 self.refless.parse_all()
867 }
868
869 fn empty(self) -> crate::Result<()> {
870 self.refless.empty()
871 }
872
873 fn non_empty(mut self) -> crate::Result<Option<Self>> {
874 self.refless = match self.refless.non_empty()? {
875 Some(refless) => refless,
876 None => return Ok(None),
877 };
878 Ok(Some(self))
879 }
880}
881
882impl<'a, Extra: 'static + Clone> PointInput for Input<'a, Extra> {
883 type Extra = Extra;
884 type WithExtra<E: 'static + Clone> = Input<'a, E>;
885
886 fn next_index(&mut self) -> usize {
887 let index = self.index.get();
888 self.index.set(index + 1);
889 index
890 }
891
892 fn resolve_arc_ref(&self) -> &Arc<dyn Resolve> {
893 self.resolve
894 }
895
896 fn extra(&self) -> &Self::Extra {
897 self.extra
898 }
899
900 fn map_extra<E: 'static + Clone>(
901 self,
902 f: impl FnOnce(&Self::Extra) -> &E,
903 ) -> Self::WithExtra<E> {
904 let Self {
905 refless,
906 resolve,
907 index,
908 extra,
909 } = self;
910 Input {
911 refless,
912 resolve,
913 index,
914 extra: f(extra),
915 }
916 }
917}
918
919pub trait ToOutput {
920 fn to_output(&self, output: &mut dyn Output);
921
922 fn data_hash(&self) -> Hash {
923 let mut output = HashOutput::default();
924 self.to_output(&mut output);
925 output.hash()
926 }
927
928 fn slice_to_output(slice: &[Self], output: &mut dyn Output)
929 where
930 Self: Sized,
931 {
932 slice.iter_to_output(output);
933 }
934
935 fn output<T: Output + Default>(&self) -> T {
936 let mut output = T::default();
937 self.to_output(&mut output);
938 output
939 }
940
941 fn vec(&self) -> Vec<u8> {
942 self.output()
943 }
944}
945
946#[derive(Default)]
947struct CountVisitor {
948 count: usize,
949}
950
951impl PointVisitor for CountVisitor {
952 fn visit<T: Traversible>(&mut self, _: &Point<T>) {
953 self.count += 1;
954 }
955}
956
957pub trait Topological {
958 fn accept_points(&self, visitor: &mut impl PointVisitor) {
959 let _ = visitor;
960 }
961
962 fn topology_hash(&self) -> Hash {
963 let mut hasher = Sha256::new();
964 self.accept_points(&mut HashVisitor(|hash| hasher.update(hash)));
965 Hash::from_sha256(hasher.finalize().into())
966 }
967
968 fn point_count(&self) -> usize {
969 let mut visitor = CountVisitor::default();
970 self.accept_points(&mut visitor);
971 visitor.count
972 }
973
974 fn topology(&self) -> TopoVec {
975 let mut topology = TopoVec::with_capacity(self.point_count());
976 self.accept_points(&mut topology);
977 topology
978 }
979}
980
981pub trait Tagged {
982 const TAGS: Tags = Tags(&[], &[]);
983
984 const HASH: Hash =
985 const { Hash::from_sha256(Self::TAGS.const_hash(sha2_const::Sha256::new()).finalize()) };
986}
987
988pub trait ParseSlice: for<'a> Parse<Input<'a>> {
989 fn parse_slice(data: &[u8], resolve: &Arc<dyn Resolve>) -> crate::Result<Self> {
990 Self::parse_slice_extra(data, resolve, &())
991 }
992}
993
994impl<T: for<'a> Parse<Input<'a>>> ParseSlice for T {}
995
996pub trait ParseSliceExtra<Extra>: for<'a> Parse<Input<'a, Extra>> {
997 fn parse_slice_extra(
998 data: &[u8],
999 resolve: &Arc<dyn Resolve>,
1000 extra: &Extra,
1001 ) -> crate::Result<Self> {
1002 let input = Input {
1003 refless: ReflessInput { data: Some(data) },
1004 resolve,
1005 index: &Cell::new(0),
1006 extra,
1007 };
1008 let object = Self::parse(input)?;
1009 Ok(object)
1010 }
1011}
1012
1013impl<T: for<'a> Parse<Input<'a, Extra>>, Extra> ParseSliceExtra<Extra> for T {}
1014
1015#[derive(ToOutput)]
1016pub struct ObjectHashes {
1017 pub tags: Hash,
1018 pub topology: Hash,
1019 pub data: Hash,
1020}
1021
1022pub trait FullHash: ToOutput + Topological + Tagged {
1023 fn hashes(&self) -> ObjectHashes {
1024 ObjectHashes {
1025 tags: Self::HASH,
1026 topology: self.topology_hash(),
1027 data: self.data_hash(),
1028 }
1029 }
1030
1031 fn full_hash(&self) -> Hash {
1032 self.hashes().data_hash()
1033 }
1034}
1035
1036impl<T: ?Sized + ToOutput + Topological + Tagged> FullHash for T {}
1037
1038pub trait Traversible: 'static + Sized + Send + Sync + FullHash {
1039 fn to_resolve(&self) -> Arc<dyn Resolve> {
1040 Arc::new(ByTopology {
1041 topology: self.topology(),
1042 })
1043 }
1044
1045 fn point(self) -> Point<Self>
1046 where
1047 Self: Clone,
1048 {
1049 Point::from_object(self)
1050 }
1051}
1052
1053impl<T: 'static + Send + Sync + FullHash> Traversible for T {}
1054
1055pub trait Object<Extra: 'static = ()>: Traversible + for<'a> Parse<Input<'a, Extra>> {}
1056
1057pub struct Tags(pub &'static [&'static str], pub &'static [&'static Self]);
1058
1059impl Tags {
1060 const fn const_hash(&self, mut hasher: sha2_const::Sha256) -> sha2_const::Sha256 {
1061 {
1062 let mut i = 0;
1063 while i < self.0.len() {
1064 hasher = hasher.update(self.0[i].as_bytes());
1065 i += 1;
1066 }
1067 }
1068 {
1069 let mut i = 0;
1070 while i < self.1.len() {
1071 hasher = self.1[i].const_hash(hasher);
1072 i += 1;
1073 }
1074 }
1075 hasher
1076 }
1077}
1078
1079pub trait Inline<Extra: 'static = ()>:
1080 Object<Extra> + for<'a> ParseInline<Input<'a, Extra>>
1081{
1082}
1083
1084impl<T: Traversible> Topological for Point<T> {
1085 fn accept_points(&self, visitor: &mut impl PointVisitor) {
1086 visitor.visit(self);
1087 }
1088
1089 fn point_count(&self) -> usize {
1090 1
1091 }
1092}
1093
1094impl<T: Object<I::Extra>, I: PointInput<Extra: Send + Sync>> ParseInline<I> for Point<T> {
1095 fn parse_inline(input: &mut I) -> crate::Result<Self> {
1096 Ok(Self::from_address_extra(
1097 input.parse_inline()?,
1098 input.resolve(),
1099 input.extra().clone(),
1100 ))
1101 }
1102}
1103
1104impl<T: Tagged> Tagged for Point<T> {
1105 const TAGS: Tags = T::TAGS;
1106}
1107
1108impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Object<Extra> for Point<T> {}
1109
1110impl<T> ToOutput for Point<T> {
1111 fn to_output(&self, output: &mut dyn Output) {
1112 self.hash().to_output(output);
1113 }
1114}
1115
1116impl<T: Object<Extra>, Extra: 'static + Send + Sync + Clone> Inline<Extra> for Point<T> {}
1117
1118pub trait Topology: Send + Sync {
1119 fn len(&self) -> usize;
1120 fn get(&self, index: usize) -> Option<&Arc<dyn Singular>>;
1121
1122 fn is_empty(&self) -> bool {
1123 self.len() == 0
1124 }
1125}
1126
1127pub trait Singular: Send + Sync + FetchBytes {
1128 fn hash(&self) -> Hash;
1129}
1130
1131pub type TopoVec = Vec<Arc<dyn Singular>>;
1132
1133impl PointVisitor for TopoVec {
1134 fn visit<T: Traversible>(&mut self, point: &Point<T>) {
1135 self.push(Arc::new(point.clone()));
1136 }
1137}
1138
1139impl<T> FetchBytes for Point<T> {
1140 fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
1141 self.origin.fetch_bytes()
1142 }
1143
1144 fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
1145 self.origin.fetch_data()
1146 }
1147}
1148
1149impl<T> Singular for Point<T> {
1150 fn hash(&self) -> Hash {
1151 self.hash.unwrap()
1152 }
1153}
1154
1155impl Topology for TopoVec {
1156 fn len(&self) -> usize {
1157 self.len()
1158 }
1159
1160 fn get(&self, index: usize) -> Option<&Arc<dyn Singular>> {
1161 (**self).get(index)
1162 }
1163}
1164
1165pub trait ParseSliceRefless: for<'a> Parse<ReflessInput<'a>> {
1166 fn parse_slice_refless(data: &[u8]) -> crate::Result<Self> {
1167 let input = ReflessInput { data: Some(data) };
1168 let object = Self::parse(input)?;
1169 Ok(object)
1170 }
1171}
1172
1173impl<T: for<'a> Parse<ReflessInput<'a>>> ParseSliceRefless for T {}
1174
1175pub trait ReflessObject:
1176 'static + Sized + Send + Sync + ToOutput + Tagged + for<'a> Parse<ReflessInput<'a>>
1177{
1178}
1179
1180pub trait ReflessInline: ReflessObject + for<'a> ParseInline<ReflessInput<'a>> {
1181 fn parse_as_inline(mut input: ReflessInput) -> crate::Result<Self> {
1182 let object = Self::parse_inline(&mut input)?;
1183 input.empty()?;
1184 Ok(object)
1185 }
1186}
1187
1188pub trait Output {
1189 fn write(&mut self, data: &[u8]);
1190}
1191
1192impl Output for Vec<u8> {
1193 fn write(&mut self, data: &[u8]) {
1194 self.extend_from_slice(data);
1195 }
1196}
1197
1198impl Output for Vec<&'static str> {
1199 fn write(&mut self, data: &[u8]) {
1200 let _ = data;
1201 }
1202}
1203
1204#[derive(Default)]
1205struct HashOutput {
1206 hasher: Sha256,
1207 at: usize,
1208}
1209
1210impl Output for HashOutput {
1211 fn write(&mut self, data: &[u8]) {
1212 self.hasher.update(data);
1213 self.at += data.len();
1214 }
1215}
1216
1217impl HashOutput {
1218 fn hash(self) -> Hash {
1219 Hash::from_sha256(self.hasher.finalize().into())
1220 }
1221}
1222
1223pub struct PointMut<'a, T: FullHash> {
1224 hash: &'a mut OptionalHash,
1225 origin: &'a mut dyn Fetch<T = T>,
1226}
1227
1228impl<T: FullHash> Deref for PointMut<'_, T> {
1229 type Target = T;
1230
1231 fn deref(&self) -> &Self::Target {
1232 self.origin.get().unwrap()
1233 }
1234}
1235
1236impl<T: FullHash> DerefMut for PointMut<'_, T> {
1237 fn deref_mut(&mut self) -> &mut Self::Target {
1238 self.origin.get_mut().unwrap()
1239 }
1240}
1241
1242impl<T: FullHash> Drop for PointMut<'_, T> {
1243 fn drop(&mut self) {
1244 self.finalize();
1245 }
1246}
1247
1248impl<'a, T: FullHash> PointMut<'a, T> {
1249 fn finalize(&mut self) {
1250 self.origin.get_mut_finalize();
1251 *self.hash = self.full_hash().into();
1252 }
1253}
1254
1255impl<T: Traversible + Clone> Point<T> {
1256 pub fn from_object(object: T) -> Self {
1257 Self::from_origin(object.full_hash(), Arc::new(LocalOrigin { object }))
1258 }
1259
1260 fn yolo_mut(&mut self) -> bool {
1261 self.origin.get().is_some()
1262 && Arc::get_mut(&mut self.origin).is_some_and(|origin| origin.get_mut().is_some())
1263 }
1264
1265 async fn prepare_yolo_origin(&mut self) -> crate::Result<()> {
1266 if !self.yolo_mut() {
1267 let object = self.origin.fetch().await?;
1268 self.origin = Arc::new(LocalOrigin { object });
1269 }
1270 Ok(())
1271 }
1272
1273 pub async fn fetch_mut(&'_ mut self) -> crate::Result<PointMut<'_, T>> {
1274 self.prepare_yolo_origin().await?;
1275 let origin = Arc::get_mut(&mut self.origin).unwrap();
1276 assert!(origin.get_mut().is_some());
1277 self.hash.clear();
1278 Ok(PointMut {
1279 hash: &mut self.hash,
1280 origin,
1281 })
1282 }
1283
1284 pub async fn fetch_ref<Extra: 'static + Send + Sync + Clone>(&mut self) -> crate::Result<&T>
1285 where
1286 T: Object<Extra> + Clone,
1287 {
1288 self.prepare_yolo_origin().await?;
1289 Ok(self.origin.get().unwrap())
1290 }
1291}
1292
1293struct LocalOrigin<T> {
1294 object: T,
1295}
1296
1297impl<T> Deref for LocalOrigin<T> {
1298 type Target = T;
1299
1300 fn deref(&self) -> &Self::Target {
1301 &self.object
1302 }
1303}
1304
1305impl<T> DerefMut for LocalOrigin<T> {
1306 fn deref_mut(&mut self) -> &mut Self::Target {
1307 &mut self.object
1308 }
1309}
1310
1311impl<T: Traversible + Clone> Fetch for LocalOrigin<T> {
1312 type T = T;
1313
1314 fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
1315 Box::pin(ready(Ok((self.object.clone(), self.object.to_resolve()))))
1316 }
1317
1318 fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
1319 Box::pin(ready(Ok(self.object.clone())))
1320 }
1321
1322 fn get(&self) -> Option<&Self::T> {
1323 Some(self)
1324 }
1325
1326 fn get_mut(&mut self) -> Option<&mut Self::T> {
1327 Some(self)
1328 }
1329}
1330
1331impl<T: Traversible + Clone> FetchBytes for LocalOrigin<T> {
1332 fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
1333 Box::pin(ready(Ok((self.object.output(), self.object.to_resolve()))))
1334 }
1335
1336 fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
1337 Box::pin(ready(Ok(self.object.output())))
1338 }
1339}
1340
1341struct ByTopology {
1342 topology: TopoVec,
1343}
1344
1345impl ByTopology {
1346 fn try_resolve(&'_ self, address: Address) -> Result<FailFuture<'_, ByteNode>> {
1347 let point = self
1348 .topology
1349 .get(address.index)
1350 .ok_or(Error::AddressOutOfBounds)?;
1351 if point.hash() != address.hash {
1352 Err(Error::ResolutionMismatch)
1353 } else {
1354 Ok(point.fetch_bytes())
1355 }
1356 }
1357
1358 fn try_resolve_data(&'_ self, address: Address) -> Result<FailFuture<'_, Vec<u8>>> {
1359 let point = self
1360 .topology
1361 .get(address.index)
1362 .ok_or(Error::AddressOutOfBounds)?;
1363 if point.hash() != address.hash {
1364 Err(Error::ResolutionMismatch)
1365 } else {
1366 Ok(point.fetch_data())
1367 }
1368 }
1369}
1370
1371impl Resolve for ByTopology {
1372 fn resolve(&'_ self, address: Address) -> FailFuture<'_, ByteNode> {
1373 self.try_resolve(address)
1374 .map_err(Err)
1375 .map_err(ready)
1376 .map_err(Box::pin)
1377 .unwrap_or_else(|x| x)
1378 }
1379
1380 fn resolve_data(&'_ self, address: Address) -> FailFuture<'_, Vec<u8>> {
1381 self.try_resolve_data(address)
1382 .map_err(Err)
1383 .map_err(ready)
1384 .map_err(Box::pin)
1385 .unwrap_or_else(|x| x)
1386 }
1387
1388 fn name(&self) -> &str {
1389 "by topology"
1390 }
1391}
1392
1393impl<T: FullHash> Fetch for Point<T> {
1394 type T = T;
1395
1396 fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
1397 self.origin.fetch_full()
1398 }
1399
1400 fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
1401 self.origin.fetch()
1402 }
1403
1404 fn get(&self) -> Option<&Self::T> {
1405 self.origin.get()
1406 }
1407
1408 fn get_mut(&mut self) -> Option<&mut Self::T> {
1409 self.hash.clear();
1410 Arc::get_mut(&mut self.origin)?.get_mut()
1411 }
1412
1413 fn get_mut_finalize(&mut self) {
1414 let origin = Arc::get_mut(&mut self.origin).unwrap();
1415 origin.get_mut_finalize();
1416 self.hash = origin.get().unwrap().full_hash().into();
1417 }
1418}
1419
1420pub trait Size {
1421 const SIZE: usize = <Self::Size as Unsigned>::USIZE;
1422 type Size: Unsigned;
1423}
1424
1425pub trait SizeExt: Size<Size: ArrayLength> + ToOutput {
1426 fn to_array(&self) -> GenericArray<u8, Self::Size> {
1427 let mut array = GenericArray::default();
1428 let mut output = ArrayOutput {
1429 data: &mut array,
1430 offset: 0,
1431 };
1432 self.to_output(&mut output);
1433 output.finalize();
1434 array
1435 }
1436}
1437
1438impl<T: Size<Size: ArrayLength> + ToOutput> SizeExt for T {}
1439
1440struct ArrayOutput<'a> {
1441 data: &'a mut [u8],
1442 offset: usize,
1443}
1444
1445impl ArrayOutput<'_> {
1446 fn finalize(self) {
1447 assert_eq!(self.offset, self.data.len());
1448 }
1449}
1450
1451impl Output for ArrayOutput<'_> {
1452 fn write(&mut self, data: &[u8]) {
1453 self.data[self.offset..][..data.len()].copy_from_slice(data);
1454 self.offset += data.len();
1455 }
1456}
1457
1458trait RainbowIterator: Sized + IntoIterator {
1459 fn iter_to_output(self, output: &mut dyn Output)
1460 where
1461 Self::Item: ToOutput,
1462 {
1463 self.into_iter().for_each(|item| item.to_output(output));
1464 }
1465
1466 fn iter_accept_points(self, visitor: &mut impl PointVisitor)
1467 where
1468 Self::Item: Topological,
1469 {
1470 self.into_iter()
1471 .for_each(|item| item.accept_points(visitor));
1472 }
1473}
1474
1475pub trait ParseInput: Sized {
1476 fn parse_chunk<'a, const N: usize>(&mut self) -> crate::Result<&'a [u8; N]>
1477 where
1478 Self: 'a;
1479 fn parse_n<'a>(&mut self, n: usize) -> crate::Result<&'a [u8]>
1480 where
1481 Self: 'a;
1482 fn parse_ahead<T: Parse<Self>>(&mut self, n: usize) -> crate::Result<T>;
1483 fn parse_compare<T: ParseInline<Self>>(&mut self, n: usize, c: &[u8]) -> Result<Option<T>>;
1484 fn parse_all<'a>(self) -> crate::Result<&'a [u8]>
1485 where
1486 Self: 'a;
1487 fn empty(self) -> crate::Result<()>;
1488 fn non_empty(self) -> crate::Result<Option<Self>>;
1489
1490 fn consume(self, f: impl FnMut(&mut Self) -> crate::Result<()>) -> crate::Result<()> {
1491 self.collect(f)
1492 }
1493
1494 fn parse_collect<T: ParseInline<Self>, B: FromIterator<T>>(self) -> crate::Result<B> {
1495 self.collect(|input| input.parse_inline())
1496 }
1497
1498 fn collect<T, B: FromIterator<T>>(
1499 self,
1500 f: impl FnMut(&mut Self) -> crate::Result<T>,
1501 ) -> crate::Result<B> {
1502 self.iter(f).collect()
1503 }
1504
1505 fn iter<T>(
1506 self,
1507 mut f: impl FnMut(&mut Self) -> crate::Result<T>,
1508 ) -> impl Iterator<Item = crate::Result<T>> {
1509 let mut state = Some(self);
1510 std::iter::from_fn(move || {
1511 let mut input = match state.take()?.non_empty() {
1512 Ok(input) => input,
1513 Err(e) => return Some(Err(e)),
1514 }?;
1515 let item = f(&mut input);
1516 state = Some(input);
1517 Some(item)
1518 })
1519 }
1520
1521 fn parse_inline<T: ParseInline<Self>>(&mut self) -> crate::Result<T> {
1522 T::parse_inline(self)
1523 }
1524
1525 fn parse<T: Parse<Self>>(self) -> crate::Result<T> {
1526 T::parse(self)
1527 }
1528
1529 fn parse_vec<T: ParseInline<Self>>(self) -> crate::Result<Vec<T>> {
1530 T::parse_vec(self)
1531 }
1532}
1533
1534pub trait PointInput: ParseInput {
1535 type Extra: 'static + Clone;
1536 type WithExtra<E: 'static + Clone>: PointInput<Extra = E, WithExtra<Self::Extra> = Self>;
1537 fn next_index(&mut self) -> usize;
1538 fn resolve_arc_ref(&self) -> &Arc<dyn Resolve>;
1539 fn resolve(&self) -> Arc<dyn Resolve> {
1540 self.resolve_arc_ref().clone()
1541 }
1542 fn resolve_ref(&self) -> &dyn Resolve {
1543 self.resolve_arc_ref().as_ref()
1544 }
1545 fn extension<T: Any>(&self) -> crate::Result<&T> {
1546 self.resolve_ref()
1547 .extension(TypeId::of::<T>())?
1548 .downcast_ref()
1549 .ok_or(Error::ExtensionType)
1550 }
1551 fn extra(&self) -> &Self::Extra;
1552 fn map_extra<E: 'static + Clone>(
1553 self,
1554 f: impl FnOnce(&Self::Extra) -> &E,
1555 ) -> Self::WithExtra<E>;
1556}
1557
1558impl<T: Sized + IntoIterator> RainbowIterator for T {}
1559
1560pub trait Parse<I: ParseInput>: Sized {
1561 fn parse(input: I) -> crate::Result<Self>;
1562}
1563
1564pub trait ParseInline<I: ParseInput>: Parse<I> {
1565 fn parse_inline(input: &mut I) -> crate::Result<Self>;
1566 fn parse_as_inline(mut input: I) -> crate::Result<Self> {
1567 let object = Self::parse_inline(&mut input)?;
1568 input.empty()?;
1569 Ok(object)
1570 }
1571 fn parse_vec(input: I) -> crate::Result<Vec<Self>> {
1572 input.parse_collect()
1573 }
1574}
1575
1576pub trait Equivalent<T>: Sized {
1583 fn into_equivalent(self) -> T;
1585 fn from_equivalent(object: T) -> Self;
1587}
1588
1589impl<U: 'static + Equivalent<T>, T: 'static> Equivalent<Point<T>> for Point<U> {
1592 fn into_equivalent(self) -> Point<T> {
1593 self.map_origin(|origin| {
1594 Arc::new(MapEquivalent {
1595 origin,
1596 map: U::into_equivalent,
1597 })
1598 })
1599 }
1600
1601 fn from_equivalent(point: Point<T>) -> Self {
1602 point.map_origin(|origin| {
1603 Arc::new(MapEquivalent {
1604 origin,
1605 map: U::from_equivalent,
1606 })
1607 })
1608 }
1609}
1610
1611struct MapEquivalent<T, F> {
1612 origin: Arc<dyn Fetch<T = T>>,
1613 map: F,
1614}
1615
1616impl<T, F> FetchBytes for MapEquivalent<T, F> {
1617 fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
1618 self.origin.fetch_bytes()
1619 }
1620
1621 fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
1622 self.origin.fetch_data()
1623 }
1624}
1625
1626trait Map1<T>: Fn(T) -> Self::U {
1627 type U;
1628}
1629
1630impl<T, U, F: Fn(T) -> U> Map1<T> for F {
1631 type U = U;
1632}
1633
1634impl<T, F: 'static + Send + Sync + Map1<T>> Fetch for MapEquivalent<T, F> {
1635 type T = F::U;
1636
1637 fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
1638 Box::pin(self.origin.fetch_full().map_ok(|(x, r)| ((self.map)(x), r)))
1639 }
1640
1641 fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
1642 Box::pin(self.origin.fetch().map_ok(&self.map))
1643 }
1644}
1645
1646impl<T: 'static + ToOutput> Point<T> {
1647 pub fn map<U>(self, map: impl 'static + Send + Sync + Fn(T) -> U) -> Point<U> {
1648 self.map_origin(|origin| Arc::new(Map { origin, map }))
1649 }
1650}
1651
1652struct Map<T, F> {
1653 origin: Arc<dyn Fetch<T = T>>,
1654 map: F,
1655}
1656
1657impl<T: ToOutput, F> FetchBytes for Map<T, F> {
1658 fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
1659 Box::pin(self.origin.fetch_full().map_ok(|(x, r)| (x.output(), r)))
1660 }
1661
1662 fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
1663 Box::pin(self.origin.fetch().map_ok(|x| x.output()))
1664 }
1665}
1666
1667impl<T: ToOutput, F: 'static + Send + Sync + Map1<T>> Fetch for Map<T, F> {
1668 type T = F::U;
1669
1670 fn fetch_full(&'_ self) -> FailFuture<'_, (Self::T, Arc<dyn Resolve>)> {
1671 Box::pin(self.origin.fetch_full().map_ok(|(x, r)| ((self.map)(x), r)))
1672 }
1673
1674 fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
1675 Box::pin(self.origin.fetch().map_ok(&self.map))
1676 }
1677}
1678
1679impl<T> MaybeHasNiche for Point<T> {
1680 type MnArray = <Hash as MaybeHasNiche>::MnArray;
1681}
1682
1683impl<T: FullHash + Default> Point<T> {
1684 pub fn is_default(&self) -> bool {
1685 self.hash() == T::default().full_hash()
1686 }
1687}
1688
1689impl<T: Default + Traversible + Clone> Default for Point<T> {
1690 fn default() -> Self {
1691 T::default().point()
1692 }
1693}
1694
1695#[test]
1696fn options() {
1697 type T0 = ();
1698 type T1 = Option<T0>;
1699 type T2 = Option<T1>;
1700 type T3 = Option<T2>;
1701 type T4 = Option<T3>;
1702 type T5 = Option<T4>;
1703 assert_eq!(T0::SIZE, 0);
1704 assert_eq!(T1::SIZE, 1);
1705 assert_eq!(T2::SIZE, 1);
1706 assert_eq!(T3::SIZE, 1);
1707 assert_eq!(T4::SIZE, 1);
1708 assert_eq!(T5::SIZE, 1);
1709 assert_eq!(Some(Some(Some(()))).vec(), [0]);
1710 assert_eq!(Some(Some(None::<()>)).vec(), [1]);
1711 assert_eq!(Some(None::<Option<()>>).vec(), [2]);
1712 assert_eq!(None::<Option<Option<()>>>.vec(), [3]);
1713
1714 assert_eq!(false.vec(), [0]);
1715 assert_eq!(true.vec(), [1]);
1716 assert_eq!(Some(false).vec(), [0]);
1717 assert_eq!(Some(true).vec(), [1]);
1718 assert_eq!(None::<bool>.vec(), [2]);
1719 assert_eq!(Some(Some(false)).vec(), [0]);
1720 assert_eq!(Some(Some(true)).vec(), [1]);
1721 assert_eq!(Some(None::<bool>).vec(), [2]);
1722 assert_eq!(None::<Option<bool>>.vec(), [3]);
1723 assert_eq!(Some(Some(Some(false))).vec(), [0]);
1724 assert_eq!(Some(Some(Some(true))).vec(), [1]);
1725 assert_eq!(Some(Some(None::<bool>)).vec(), [2]);
1726 assert_eq!(Some(None::<Option<bool>>).vec(), [3]);
1727 assert_eq!(None::<Option<Option<bool>>>.vec(), [4]);
1728 assert_eq!(Option::<Point<()>>::SIZE, HASH_SIZE);
1729 assert_eq!(Some(()).vec(), [0]);
1730 assert_eq!(Some(((), ())).vec(), [0]);
1731 assert_eq!(Some(((), true)).vec(), [1]);
1732 assert_eq!(Some((true, true)).vec(), [1, 1]);
1733 assert_eq!(Some((Some(true), true)).vec(), [1, 1]);
1734 assert_eq!(Some((None::<bool>, true)).vec(), [2, 1]);
1735 assert_eq!(Some((true, None::<bool>)).vec(), [1, 2]);
1736 assert_eq!(None::<(Option<bool>, bool)>.vec(), [3, 2]);
1737 assert_eq!(None::<(bool, Option<bool>)>.vec(), [2, 3]);
1738 assert_eq!(Some(Some((Some(true), Some(true)))).vec(), [1, 1],);
1739 assert_eq!(Option::<Point<()>>::SIZE, HASH_SIZE);
1740 assert_eq!(Option::<Option<Point<()>>>::SIZE, HASH_SIZE);
1741 assert_eq!(Option::<Option<Option<Point<()>>>>::SIZE, HASH_SIZE);
1742}