timely_container/
lib.rs

1//! Specifications for containers
2
3#![forbid(missing_docs)]
4
5use std::collections::VecDeque;
6
7/// A type containing a number of records accounted for by progress tracking.
8///
9/// The object stores a number of updates and thus is able to describe it count
10/// (`update_count()`) and whether it is empty (`is_empty()`). It is empty if the
11/// update count is zero.
12pub trait Accountable {
13    /// The number of records
14    ///
15    /// This number is used in progress tracking to confirm the receipt of some number
16    /// of outstanding records, and it is highly load bearing. The main restriction is
17    /// imposed on the `LengthPreservingContainerBuilder` trait, whose implementors
18    /// must preserve the number of records.
19    fn record_count(&self) -> i64;
20
21    /// Determine if this contains any updates, corresponding to `update_count() == 0`.
22    /// It is a correctness error for this to be anything other than `self.record_count() == 0`.
23    #[inline] fn is_empty(&self) -> bool { self.record_count() == 0 }
24}
25
26/// A container that can drain itself.
27///
28/// Draining the container presents items in an implementation-specific order.
29/// The container is in an undefined state after calling [`drain`]. Dropping
30/// the iterator also leaves the container in an undefined state.
31pub trait DrainContainer {
32    /// The type of elements when draining the container.
33    type Item<'a> where Self: 'a;
34    /// Iterator type when draining the container.
35    type DrainIter<'a>: Iterator<Item=Self::Item<'a>> where Self: 'a;
36    /// Returns an iterator that drains the contents of this container.
37    /// Drain leaves the container in an undefined state.
38    fn drain(&mut self) -> Self::DrainIter<'_>;
39}
40
41/// A container that can be sized and reveals its capacity.
42pub trait SizableContainer {
43    /// Indicates that the container is "full" and should be shipped.
44    fn at_capacity(&self) -> bool;
45    /// Restores `self` to its desired capacity, if it has one.
46    ///
47    /// The `stash` argument is available, and may have the intended capacity.
48    /// However, it may be non-empty, and may be of the wrong capacity. The
49    /// method should guard against these cases.
50    ///
51    /// Assume that the `stash` is in an undefined state, and properly clear it
52    /// before re-using it.
53    fn ensure_capacity(&mut self, stash: &mut Option<Self>) where Self: Sized;
54}
55
56/// A container that can absorb items of a specific type.
57pub trait PushInto<T> {
58    /// Push item into self.
59    fn push_into(&mut self, item: T);
60}
61
62/// A type that can build containers from items.
63///
64/// An implementation needs to absorb elements, and later reveal equivalent information
65/// chunked into individual containers, but is free to change the data representation to
66/// better fit the properties of the container.
67///
68/// Types implementing this trait should provide appropriate [`PushInto`] implementations such
69/// that users can push the expected item types.
70///
71/// The owner extracts data in two ways. The opportunistic [`Self::extract`] method returns
72/// any ready data, but doesn't need to produce partial outputs. In contrast, [`Self::finish`]
73/// needs to produce all outputs, even partial ones. Caller should repeatedly call the functions
74/// to drain pending or finished data.
75///
76/// The caller should consume the containers returned by [`Self::extract`] and
77/// [`Self::finish`]. Implementations can recycle buffers, but should ensure that they clear
78/// any remaining elements.
79///
80/// Implementations are allowed to re-use the contents of the mutable references left by the caller,
81/// but they should ensure that they clear the contents before doing so.
82///
83/// For example, a consolidating builder can aggregate differences in-place, but it has
84/// to ensure that it preserves the intended information.
85///
86/// The trait does not prescribe any specific ordering guarantees, and each implementation can
87/// decide to represent a push order for `extract` and `finish`, or not.
88pub trait ContainerBuilder: Default {
89    /// The container type we're building.
90    // The container is `Clone` because `Tee` requires it, otherwise we need to repeat it
91    // all over Timely. `'static` because we don't want lifetimes everywhere.
92    type Container;
93    /// Extract assembled containers, potentially leaving unfinished data behind. Can
94    /// be called repeatedly, for example while the caller can send data.
95    ///
96    /// Returns a `Some` if there is data ready to be shipped, and `None` otherwise.
97    #[must_use]
98    fn extract(&mut self) -> Option<&mut Self::Container>;
99    /// Extract assembled containers and any unfinished data. Should
100    /// be called repeatedly until it returns `None`.
101    #[must_use]
102    fn finish(&mut self) -> Option<&mut Self::Container>;
103    /// Indicates a good moment to release resources.
104    ///
105    /// By default, does nothing. Callers first needs to drain the contents using [`Self::finish`]
106    /// before calling this function. The implementation should not change the contents of the
107    /// builder.
108    #[inline]
109    fn relax(&mut self) { }
110}
111
112/// A wrapper trait indicating that the container building will preserve the number of records.
113///
114/// Specifically, the sum of record counts of all extracted and finished containers must equal the
115/// number of accounted records that are pushed into the container builder.
116/// If you have any questions about this trait you are best off not implementing it.
117pub trait LengthPreservingContainerBuilder : ContainerBuilder { }
118
119/// A default container builder that uses length and preferred capacity to chunk data.
120///
121/// Maintains a single empty allocation between [`Self::push_into`] and [`Self::extract`], but not
122/// across [`Self::finish`] to maintain a low memory footprint.
123///
124/// Maintains FIFO order.
125#[derive(Default, Debug)]
126pub struct CapacityContainerBuilder<C>{
127    /// Container that we're writing to.
128    current: C,
129    /// Empty allocation.
130    empty: Option<C>,
131    /// Completed containers pending to be sent.
132    pending: VecDeque<C>,
133}
134
135impl<T, C: SizableContainer + Default + PushInto<T>> PushInto<T> for CapacityContainerBuilder<C> {
136    #[inline]
137    fn push_into(&mut self, item: T) {
138        // Ensure capacity
139        self.current.ensure_capacity(&mut self.empty);
140
141        // Push item
142        self.current.push_into(item);
143
144        // Maybe flush
145        if self.current.at_capacity() {
146            self.pending.push_back(std::mem::take(&mut self.current));
147        }
148    }
149}
150
151impl<C: Accountable + Default> ContainerBuilder for CapacityContainerBuilder<C> {
152    type Container = C;
153
154    #[inline]
155    fn extract(&mut self) -> Option<&mut C> {
156        if let Some(container) = self.pending.pop_front() {
157            self.empty = Some(container);
158            self.empty.as_mut()
159        } else {
160            None
161        }
162    }
163
164    #[inline]
165    fn finish(&mut self) -> Option<&mut C> {
166        if !self.current.is_empty() {
167            self.pending.push_back(std::mem::take(&mut self.current));
168        }
169        self.empty = self.pending.pop_front();
170        self.empty.as_mut()
171    }
172}
173
174impl<C: Accountable + SizableContainer + Default> LengthPreservingContainerBuilder for CapacityContainerBuilder<C> { }
175
176impl<T> Accountable for Vec<T> {
177    #[inline] fn record_count(&self) -> i64 { i64::try_from(Vec::len(self)).unwrap() }
178    #[inline] fn is_empty(&self) -> bool { Vec::is_empty(self) }
179}
180
181impl<T> DrainContainer for Vec<T> {
182    type Item<'a> = T where T: 'a;
183    type DrainIter<'a> = std::vec::Drain<'a, T> where Self: 'a;
184    #[inline] fn drain(&mut self) -> Self::DrainIter<'_> {
185        self.drain(..)
186    }
187}
188
189impl<T> SizableContainer for Vec<T> {
190    fn at_capacity(&self) -> bool {
191        self.len() == self.capacity()
192    }
193    fn ensure_capacity(&mut self, stash: &mut Option<Self>) {
194        if self.capacity() == 0 {
195            *self = stash.take().unwrap_or_default();
196            self.clear();
197        }
198        let preferred = buffer::default_capacity::<T>();
199        if self.capacity() < preferred {
200            self.reserve(preferred - self.capacity());
201        }
202    }
203}
204
205impl<T> PushInto<T> for Vec<T> {
206    #[inline]
207    fn push_into(&mut self, item: T) {
208        self.push(item)
209    }
210}
211
212
213impl<T: Clone> PushInto<&T> for Vec<T> {
214    #[inline]
215    fn push_into(&mut self, item: &T) {
216        self.push(item.clone())
217    }
218}
219
220impl<T: Clone> PushInto<&&T> for Vec<T> {
221    #[inline]
222    fn push_into(&mut self, item: &&T) {
223        self.push_into(*item)
224    }
225}
226
227mod rc {
228    impl<T: crate::Accountable> crate::Accountable for std::rc::Rc<T> {
229        #[inline] fn record_count(&self) -> i64 { self.as_ref().record_count() }
230        #[inline] fn is_empty(&self) -> bool { self.as_ref().is_empty() }
231    }
232    impl<T> crate::DrainContainer for std::rc::Rc<T>
233    where
234        for<'a> &'a T: IntoIterator
235    {
236        type Item<'a> = <&'a T as IntoIterator>::Item where Self: 'a;
237        type DrainIter<'a> = <&'a T as IntoIterator>::IntoIter where Self: 'a;
238        #[inline] fn drain(&mut self) -> Self::DrainIter<'_> { self.into_iter() }
239    }
240}
241
242mod arc {
243    impl<T: crate::Accountable> crate::Accountable for std::sync::Arc<T> {
244        #[inline] fn record_count(&self) -> i64 { self.as_ref().record_count() }
245        #[inline] fn is_empty(&self) -> bool { self.as_ref().is_empty() }
246    }
247    impl<T> crate::DrainContainer for std::sync::Arc<T>
248    where
249        for<'a> &'a T: IntoIterator
250    {
251        type Item<'a> = <&'a T as IntoIterator>::Item where Self: 'a;
252        type DrainIter<'a> = <&'a T as IntoIterator>::IntoIter where Self: 'a;
253        #[inline] fn drain(&mut self) -> Self::DrainIter<'_> { self.into_iter() }
254    }
255}
256
257pub mod buffer {
258    //! Functionality related to calculating default buffer sizes
259
260    /// The upper limit for buffers to allocate, size in bytes. [default_capacity] converts
261    /// this to size in elements.
262    pub const BUFFER_SIZE_BYTES: usize = 1 << 13;
263
264    /// The maximum buffer capacity in elements. Returns a number between [BUFFER_SIZE_BYTES]
265    /// and 1, inclusively.
266    pub const fn default_capacity<T>() -> usize {
267        let size = std::mem::size_of::<T>();
268        if size == 0 {
269            BUFFER_SIZE_BYTES
270        } else if size <= BUFFER_SIZE_BYTES {
271            BUFFER_SIZE_BYTES / size
272        } else {
273            1
274        }
275    }
276}