Skip to content

Commit ae99a1b

Browse files
Use optimized merge subroutine for Relation::merge
1 parent 50567d6 commit ae99a1b

File tree

1 file changed

+1
-58
lines changed

1 file changed

+1
-58
lines changed

src/lib.rs

Lines changed: 1 addition & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
#![forbid(missing_docs)]
1313

1414
use std::cell::RefCell;
15-
use std::cmp::Ordering;
1615
use std::io::Write;
1716
use std::iter::FromIterator;
1817
use std::rc::Rc;
@@ -46,63 +45,7 @@ pub struct Relation<Tuple: Ord> {
4645
impl<Tuple: Ord> Relation<Tuple> {
4746
/// Merges two relations into their union.
4847
pub fn merge(self, other: Self) -> Self {
49-
let Relation {
50-
elements: mut elements1,
51-
} = self;
52-
let Relation {
53-
elements: mut elements2,
54-
} = other;
55-
56-
// If one of the element lists is zero-length, we don't need to do any work
57-
if elements1.is_empty() {
58-
return Relation {
59-
elements: elements2,
60-
};
61-
}
62-
63-
if elements2.is_empty() {
64-
return Relation {
65-
elements: elements1,
66-
};
67-
}
68-
69-
// Make sure that elements1 starts with the lower element
70-
// Will not panic since both collections must have at least 1 element at this point
71-
if elements1[0] > elements2[0] {
72-
std::mem::swap(&mut elements1, &mut elements2);
73-
}
74-
75-
// Fast path for when all the new elements are after the exiting ones
76-
if elements1[elements1.len() - 1] < elements2[0] {
77-
elements1.extend(elements2.into_iter());
78-
// println!("fast path");
79-
return Relation {
80-
elements: elements1,
81-
};
82-
}
83-
84-
let mut elements = Vec::with_capacity(elements1.len() + elements2.len());
85-
let mut elements1 = elements1.drain(..);
86-
let mut elements2 = elements2.drain(..).peekable();
87-
88-
elements.push(elements1.next().unwrap());
89-
if elements.first() == elements2.peek() {
90-
elements2.next();
91-
}
92-
93-
for elem in elements1 {
94-
while elements2.peek().map(|x| x.cmp(&elem)) == Some(Ordering::Less) {
95-
elements.push(elements2.next().unwrap());
96-
}
97-
if elements2.peek().map(|x| x.cmp(&elem)) == Some(Ordering::Equal) {
98-
elements2.next();
99-
}
100-
elements.push(elem);
101-
}
102-
103-
// Finish draining second list
104-
elements.extend(elements2);
105-
48+
let elements = merge::merge_unique(self.elements, other.elements);
10649
Relation { elements }
10750
}
10851

0 commit comments

Comments
 (0)