From aa9550254a2880ebd645c9331593f0ac62c462fb Mon Sep 17 00:00:00 2001 From: Diego Ongaro Date: Tue, 20 Feb 2018 15:37:46 -0800 Subject: [PATCH] Fix reverse iteration from a given key Now when you reverse iterate past the last key, it goes backwards from the end. When you reverse iterate before the first key, you get nothing out. Note: This is a breaking change if users have come to depend on the old behavior. --- src/db.rs | 9 ++++++--- tests/test_iterator.rs | 9 +++++++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/db.rs b/src/db.rs index c292283..a26fae9 100644 --- a/src/db.rs +++ b/src/db.rs @@ -466,10 +466,13 @@ impl DBIterator { self.raw.seek_to_last(); self.direction = Direction::Reverse; } - IteratorMode::From(key, dir) => { - // TODO: Should use seek_for_prev when reversing + IteratorMode::From(key, Direction::Forward) => { self.raw.seek(key); - self.direction = dir; + self.direction = Direction::Forward; + } + IteratorMode::From(key, Direction::Reverse) => { + self.raw.seek_for_prev(key); + self.direction = Direction::Reverse; } }; diff --git a/tests/test_iterator.rs b/tests/test_iterator.rs index ff6b62c..3cb368f 100644 --- a/tests/test_iterator.rs +++ b/tests/test_iterator.rs @@ -122,6 +122,11 @@ pub fn test_iterator() { let expected = vec![(cba(&k2), cba(&v2)), (cba(&k1), cba(&v1))]; assert_eq!(iterator1.collect::>(), expected); } + { + let iterator1 = db.iterator(IteratorMode::From(b"zz", Direction::Reverse)); + let expected = vec![(cba(&k4), cba(&v4)), (cba(&k3), cba(&v3))]; + assert_eq!(iterator1.take(2).collect::>(), expected); + } { let iterator1 = db.iterator(IteratorMode::From(b"k0", Direction::Forward)); assert!(iterator1.valid()); @@ -132,13 +137,13 @@ pub fn test_iterator() { let iterator4 = db.iterator(IteratorMode::From(b"k5", Direction::Forward)); assert!(!iterator4.valid()); let iterator5 = db.iterator(IteratorMode::From(b"k0", Direction::Reverse)); - assert!(iterator5.valid()); + assert!(!iterator5.valid()); let iterator6 = db.iterator(IteratorMode::From(b"k1", Direction::Reverse)); assert!(iterator6.valid()); let iterator7 = db.iterator(IteratorMode::From(b"k11", Direction::Reverse)); assert!(iterator7.valid()); let iterator8 = db.iterator(IteratorMode::From(b"k5", Direction::Reverse)); - assert!(!iterator8.valid()); + assert!(iterator8.valid()); } { let mut iterator1 = db.iterator(IteratorMode::From(b"k4", Direction::Forward));