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