Skip to main content

primitives/correlated_randomness/bundler/
mod.rs

1use std::{
2    fmt::Debug,
3    ops::{Add, AddAssign, Sub, SubAssign},
4};
5
6use crate::correlated_randomness::bundler::errors::BundlerError;
7
8pub mod errors;
9/// Bundles together multiple correlation generators/streams to fetch all correlations
10///  required by a given consumer, e.g., a circuit, a protocol, a layer...
11pub trait Bundler {
12    /// A type to hold the futures to all requested correlations.
13    type Iterator: BundleIterator;
14
15    /// Fetches the requested correlations and returns a ready-to-use iterator.
16    fn fetch(
17        &mut self,
18        size: &<Self::Iterator as BundleIterator>::Size,
19    ) -> Result<Self::Iterator, BundlerError>;
20
21    /// Fetches the requested correlations and returns a ready-to-use iterator.
22    fn fetch_for<Consumer: BundleConsumer<Iterator = Self::Iterator>>(
23        &mut self,
24        consumer: &Consumer,
25    ) -> Result<Self::Iterator, BundlerError> {
26        let size = consumer.required_preprocessing();
27        self.fetch(&size)
28    }
29}
30
31impl<B: Bundler> Bundler for &mut B {
32    type Iterator = B::Iterator;
33
34    fn fetch(
35        &mut self,
36        size: &<Self::Iterator as BundleIterator>::Size,
37    ) -> Result<Self::Iterator, BundlerError> {
38        (**self).fetch(size)
39    }
40}
41
42/// A consumer of a bundle of correlations, e.g., a circuit, a protocol, a layer...
43pub trait BundleConsumer {
44    /// An iterator holding futures to all correlations required by the consumer
45    ///  (e.g., F_q triples, binary singlets, ...)
46    type Iterator: BundleIterator;
47
48    /// Returns the size of the preprocessing required by the consumer.
49    fn required_preprocessing(&self) -> <Self::Iterator as BundleIterator>::Size;
50
51    /// Fetches all preprocessing required by `consumer` and returns a ready-to-use iterator.
52    fn fetch_preprocessing_from<PB: Bundler<Iterator = Self::Iterator>>(
53        &self,
54        bundler: &mut PB,
55    ) -> Result<Self::Iterator, BundlerError> {
56        let size = self.required_preprocessing();
57        bundler.fetch(&size)
58    }
59}
60
61/// An iterator that holds futures to all correlations required by a consumer.
62pub trait BundleIterator {
63    /// The size of the iterator, i.e., the number of correlations per type that it holds.
64    type Size: Debug + Clone + Default + Eq + Add + Sub + AddAssign + SubAssign;
65
66    /// Returns the size of the iterator, i.e., the number of correlations per type that it holds.
67    fn len(&self) -> Self::Size;
68
69    /// Returns `true` if the iterator is empty, i.e., it holds no correlations.
70    fn is_empty(&self) -> bool {
71        self.len() == Self::Size::default()
72    }
73}