Skip to content

Commit c6e7890

Browse files
author
blake2-ppc
committed
dlist: Fix bug in DList::merge
Did not properly allow runs from the `other` list to be merged in. The test case was using a wrong expected value. Edited docs for merge so they explain more clearly what it does. Also make sure insert_ordered is marked pub.
1 parent 1ee54a8 commit c6e7890

File tree

1 file changed

+18
-11
lines changed

1 file changed

+18
-11
lines changed

src/libextra/dlist.rs

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -300,19 +300,26 @@ impl<T> DList<T> {
300300
self.push_back(elt);
301301
}
302302

303-
/// Merge, using the function `f`; take `a` if `f(a, b)` is true, else `b`.
303+
/// Merge DList `other` into this DList, using the function `f`.
304+
/// Iterate the both DList with `a` from self and `b` from `other`, and
305+
/// put `a` in the result if `f(a, b)` is true, else `b`.
304306
///
305307
/// O(max(N, M))
306308
pub fn merge(&mut self, mut other: DList<T>, f: &fn(&T, &T) -> bool) {
307309
{
308310
let mut it = self.mut_iter();
311+
let mut elt = it.next();
309312
loop {
310-
match (it.next(), other.front()) {
311-
(None , _ ) => break,
312-
(_ , None ) => return,
313-
(Some(x), Some(y)) => if f(x, y) { loop }
313+
let take_a = match (&mut elt, other.front()) {
314+
(_ , None) => return,
315+
(&None, _ ) => break,
316+
(&Some(ref mut x), Some(y)) => f(*x, y),
317+
};
318+
if take_a {
319+
elt = it.next()
320+
} else {
321+
it.insert_before(other.pop_front().unwrap());
314322
}
315-
it.insert_before(other.pop_front().unwrap());
316323
}
317324
}
318325
self.append(other);
@@ -351,11 +358,11 @@ impl<T> DList<T> {
351358
}
352359
}
353360

354-
/// Insert sorted in ascending order
355-
///
356-
/// O(N)
357361
impl<T: cmp::TotalOrd> DList<T> {
358-
fn insert_ordered(&mut self, elt: T) {
362+
/// Insert `elt` sorted in ascending order
363+
///
364+
/// O(N)
365+
pub fn insert_ordered(&mut self, elt: T) {
359366
self.insert_when(elt, |a, b| a.cmp(b) != cmp::Less);
360367
}
361368
}
@@ -758,7 +765,7 @@ mod tests {
758765
assert_eq!(m.len(), len);
759766
check_links(&m);
760767
let res = m.consume_iter().collect::<~[int]>();
761-
assert_eq!(res, ~[-1, 0, 0, 1, 0, 3, 5, 6, 7, 2, 7, 7, 9]);
768+
assert_eq!(res, ~[-1, 0, 0, 0, 1, 3, 5, 6, 7, 2, 7, 7, 9]);
762769
}
763770

764771
#[test]

0 commit comments

Comments
 (0)