Skip to main content

micromegas_transit/
heterogeneous_queue.rs

1use crate::UserDefinedType;
2
3pub trait HeterogeneousQueue {
4    type Item;
5    fn iter(&self) -> QueueIterator<'_, Self, Self::Item>
6    where
7        Self: Sized;
8    fn len_bytes(&self) -> usize;
9    fn nb_objects(&self) -> usize;
10    fn capacity_bytes(&self) -> usize;
11    fn read_value_at_offset(&self, offset: usize) -> (Self::Item, usize);
12    fn new(buffer_size: usize) -> Self;
13    fn reflect_contained() -> Vec<UserDefinedType>;
14    fn as_bytes(&self) -> &[u8];
15    /// Appends the records of `other`, which must be a queue of the same type so that the
16    /// type indices mean the same thing.
17    fn extend_from(&mut self, other: &Self);
18}
19
20pub struct QueueIterator<'a, QueueT, ValueT> {
21    queue: &'a QueueT,
22    offset: usize,
23    phantom: std::marker::PhantomData<&'a ValueT>,
24}
25
26impl<'a, QueueT, ValueT> QueueIterator<'a, QueueT, ValueT> {
27    pub fn begin(queue: &'a QueueT) -> Self {
28        let offset = 0;
29        Self {
30            queue,
31            offset,
32            phantom: std::marker::PhantomData,
33        }
34    }
35}
36
37impl<QueueT: HeterogeneousQueue, ValueT> core::iter::Iterator
38    for QueueIterator<'_, QueueT, ValueT>
39{
40    type Item = QueueT::Item;
41
42    fn next(&mut self) -> Option<Self::Item> {
43        if self.offset >= self.queue.len_bytes() {
44            None
45        } else {
46            let (obj, next_offset) = self.queue.read_value_at_offset(self.offset);
47            self.offset = next_offset;
48            Some(obj)
49        }
50    }
51}