1pub mod heap_array;
2pub mod identifiers;
3
4use std::{error::Error, fmt::Debug, ops::Add};
5
6pub use heap_array::{HeapArray, HeapMatrix, RowMajorHeapMatrix};
7pub use identifiers::{FaultyPeer, PeerId, PeerIndex, PeerNumber, ProtocolInfo, SessionId};
8use subtle::Choice;
9use typenum::{NonZero, Unsigned, B1};
10
11use crate::utils::IntoExactSizeIterator;
12
13pub trait Positive: Unsigned + NonZero + Debug + Eq + Send + Clone {
17 const SIZE: usize;
18}
19impl<T: Unsigned + NonZero + Debug + Eq + Send + Clone> Positive for T {
20 const SIZE: usize = <T as Unsigned>::USIZE;
21}
22
23pub trait NonNegative: Unsigned + Debug + Eq + Send + Clone {}
25impl<T: Unsigned + Debug + Eq + Send + Clone> NonNegative for T {}
26
27pub trait PositivePlusOne: Positive + Add<B1, Output: Positive> {}
30impl<T: Positive + Add<B1, Output: Positive>> PositivePlusOne for T {}
31
32pub trait Batched: Sized + IntoExactSizeIterator<Item = <Self as Batched>::Item> {
36 type Item;
38
39 type Size: Positive;
41
42 fn batch_size() -> usize {
44 Self::Size::SIZE
45 }
46}
47
48pub trait ConditionallySelectable: Sized {
52 fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self;
59}
60
61impl<T: subtle::ConditionallySelectable> ConditionallySelectable for T {
62 #[inline]
63 fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
64 <T as subtle::ConditionallySelectable>::conditional_select(a, b, choice)
65 }
66}
67
68pub trait CollectAll<T, E: Error + From<Vec<E>>>: Iterator<Item = Result<T, E>> + Sized {
72 fn collect_all<TC: FromIterator<T> + Extend<T> + Default>(self) -> Result<TC, E> {
76 let (values, errors): (TC, Vec<E>) =
77 itertools::Itertools::partition_map(self, |v| match v {
78 Ok(v) => itertools::Either::Left(v),
79 Err(e) => itertools::Either::Right(e),
80 });
81 match errors.len() {
82 0 => Ok(values),
83 1 => Err(errors.into_iter().next().unwrap()),
84 _ => Err(E::from(errors)),
85 }
86 }
87
88 fn collect_all_vec(self) -> Result<Vec<T>, E> {
92 self.collect_all::<Vec<T>>()
93 }
94
95 fn collect_errors(self) -> Result<(), E> {
97 let errors: Vec<E> = self.filter_map(Result::err).collect();
98 match errors.len() {
99 0 => Ok(()),
100 1 => Err(errors.into_iter().next().unwrap()),
101 _ => Err(E::from(errors)),
102 }
103 }
104}
105
106impl<T, E: Error + From<Vec<E>>, I: Iterator<Item = Result<T, E>>> CollectAll<T, E> for I {}