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