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