1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//! A wrapper which accounts records pulled past in a shared count map.

use std::rc::Rc;
use std::cell::RefCell;

use crate::dataflow::channels::Bundle;
use crate::progress::ChangeBatch;
use crate::communication::Pull;
use crate::Container;

/// A wrapper which accounts records pulled past in a shared count map.
pub struct Counter<T: Ord+Clone+'static, C, P: Pull<Bundle<T, C>>> {
    pullable: P,
    consumed: Rc<RefCell<ChangeBatch<T>>>,
    phantom: ::std::marker::PhantomData<C>,
}

/// A guard type that updates the change batch counts on drop
pub struct ConsumedGuard<T: Ord + Clone + 'static> {
    consumed: Rc<RefCell<ChangeBatch<T>>>,
    time: Option<T>,
    len: usize,
}

impl<T:Ord+Clone+'static> ConsumedGuard<T> {
    pub(crate) fn time(&self) -> &T {
        &self.time.as_ref().unwrap()
    }
}

impl<T:Ord+Clone+'static> Drop for ConsumedGuard<T> {
    fn drop(&mut self) {
        // SAFETY: we're in a Drop impl, so this runs at most once
        let time = self.time.take().unwrap();
        self.consumed.borrow_mut().update(time, self.len as i64);
    }
}

impl<T:Ord+Clone+'static, C: Container, P: Pull<Bundle<T, C>>> Counter<T, C, P> {
    /// Retrieves the next timestamp and batch of data.
    #[inline]
    pub fn next(&mut self) -> Option<&mut Bundle<T, C>> {
        self.next_guarded().map(|(_guard, bundle)| bundle)
    }

    #[inline]
    pub(crate) fn next_guarded(&mut self) -> Option<(ConsumedGuard<T>, &mut Bundle<T, C>)> {
        if let Some(message) = self.pullable.pull() {
            let guard = ConsumedGuard {
                consumed: Rc::clone(&self.consumed),
                time: Some(message.time.clone()),
                len: message.data.len(),
            };
            Some((guard, message))
        }
        else { None }
    }
}

impl<T:Ord+Clone+'static, C, P: Pull<Bundle<T, C>>> Counter<T, C, P> {
    /// Allocates a new `Counter` from a boxed puller.
    pub fn new(pullable: P) -> Self {
        Counter {
            phantom: ::std::marker::PhantomData,
            pullable,
            consumed: Rc::new(RefCell::new(ChangeBatch::new())),
        }
    }
    /// A references to shared changes in counts, for cloning or draining.
    pub fn consumed(&self) -> &Rc<RefCell<ChangeBatch<T>>> {
        &self.consumed
    }
}