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
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
//! Frame Heap

use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::fmt::Debug;

use crate::{Frame, Op, Terminator};

/// Helper trait for configuring `Heap`s order.
pub trait FrameOrd<'a>: From<Frame<'a>> + Iterator<Item = Op> {
    /// Return the first Op in the Frame.
    fn peek<'b>(&'b self) -> Option<&'b Op>;
    /// Compare `a` and `b` using the primary comparison function.
    fn primary_cmp(a: &Op, b: &Op) -> Ordering;
    /// Compare `a` and `b` using the secondary comparison function.
    fn secondary_cmp(a: &Op, b: &Op) -> Ordering;
}

#[derive(Debug)]
struct Wrapper<T> {
    inner: T,
}

impl<'a, T> PartialOrd for Wrapper<T>
where
    T: FrameOrd<'a>,
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<'a, T> Ord for Wrapper<T>
where
    T: FrameOrd<'a>,
{
    fn cmp(&self, other: &Self) -> Ordering {
        match (self.inner.peek(), other.inner.peek()) {
            (None, None) => Ordering::Equal,
            (None, Some(_)) => Ordering::Less,
            (Some(_), None) => Ordering::Greater,
            (Some(a), Some(b)) => {
                let ret = T::primary_cmp(a, b);
                if ret == Ordering::Equal {
                    T::secondary_cmp(a, b)
                } else {
                    ret
                }
            }
        }
        .reverse()
    }
}

impl<'a, T> PartialEq for Wrapper<T>
where
    T: FrameOrd<'a>,
{
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl<'a, T> Eq for Wrapper<T> where T: FrameOrd<'a> {}

/// Am Iterator heap of Frames.
pub struct Heap<T> {
    heap: BinaryHeap<Wrapper<T>>,
    top: Option<Op>,
}

impl<'a, T> Heap<T>
where
    T: FrameOrd<'a> + Debug,
{
    /// Create a new Heap from `batch`.
    pub fn new(batch: Vec<Frame<'a>>) -> Self {
        let mut heap = BinaryHeap::default();

        for mut f in batch {
            loop {
                match f.peek().cloned() {
                    Some(Op { term: Terminator::Header, .. })
                    | Some(Op { term: Terminator::Query, .. }) => {
                        f.next();
                    }
                    Some(_) => {
                        heap.push(Wrapper { inner: f.into() });
                        break;
                    }
                    None => {
                        break;
                    }
                }
            }
        }

        let mut ret = Heap { heap: heap, top: None };
        let top = ret.advance();
        ret.top = top;
        ret
    }

    /// Returns the smallest of all initial Ops of all Frames.
    pub fn top<'b>(&'b self) -> Option<&'b Op> {
        self.top.as_ref()
    }

    /// Returns and removes the smallest of all initial Ops of all Frames.
    pub fn pop(&mut self) -> Option<Op> {
        use std::mem;

        if self.top.is_some() {
            let mut ret = None;

            mem::swap(&mut ret, &mut self.top);
            self.top = self.advance();
            ret
        } else {
            None
        }
    }

    fn advance(&mut self) -> Option<Op> {
        loop {
            match self.heap.pop() {
                Some(mut frm) => {
                    match frm.inner.peek().cloned() {
                        Some(Op { term: Terminator::Header, .. })
                        | Some(Op { term: Terminator::Query, .. }) => {
                            frm.inner.next();
                            self.heap.push(frm);
                            /* continue */
                        }
                        Some(op) => {
                            self.heap.push(frm);
                            self.drain(&op);
                            return Some(op);
                        }
                        None => {}
                    }
                }
                None => {
                    return None;
                }
            }
        }
    }

    fn drain(&mut self, op: &Op) {
        let mut frames = Vec::with_capacity(self.heap.len());

        while let Some(mut frm) = self.heap.pop() {
            loop {
                match frm.inner.peek().cloned() {
                    Some(ref p) if T::primary_cmp(p, op) == Ordering::Equal => {
                        frm.inner.next();
                    }
                    _ => {
                        break;
                    }
                }
            }
            frames.push(frm);
        }

        self.heap.extend(frames);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use uuid::UUID;

    use crate::Heap;

    #[derive(Debug)]
    struct HeapOrd<'a>(Frame<'a>);

    impl<'a> FrameOrd<'a> for HeapOrd<'a> {
        fn primary_cmp(a: &Op, b: &Op) -> Ordering {
            if a.event == b.event {
                UUID::weak_cmp(&a.location, &b.location)
            } else {
                UUID::weak_cmp(&b.event, &a.event)
            }
        }

        fn secondary_cmp(a: &Op, b: &Op) -> Ordering {
            UUID::weak_cmp(&a.location, &b.location)
        }

        fn peek(&self) -> Option<&Op> {
            self.0.peek()
        }
    }

    impl<'a> Iterator for HeapOrd<'a> {
        type Item = Op;

        fn next(&mut self) -> Option<Op> {
            self.0.next()
        }
    }

    impl<'a> From<Frame<'a>> for HeapOrd<'a> {
        fn from(frame: Frame<'a>) -> Self {
            HeapOrd(frame)
        }
    }

    #[test]
    fn merge() {
        let frame_a = Frame::parse("*rga#test@0:0!@1'A'@2'B'"); //  D E A C B
        let frame_b = Frame::parse("*rga#test@0:0!@1'A'@3'C'");
        let frame_c = Frame::parse("*rga#test@0:0!@4'D'@5'E'");
        let mut frame_r = Frame::parse("*rga#test@4'D',@5'E'@1'A'@3'C'@2'B'");
        let mut heap = Heap::<HeapOrd>::new(vec![frame_a, frame_b, frame_c]);

        while let op @ Some(_) = heap.pop() {
            assert_eq!(frame_r.next(), op);
        }

        assert!(frame_r.next().is_none());
    }
}