rust_rocksdb/db_iterator.rs
1// Copyright 2020 Tyler Neely
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::{
16 Error, ReadOptions, WriteBatch,
17 db::{DB, DBAccess},
18 ffi,
19};
20use libc::{c_char, c_uchar, size_t};
21use std::mem::ManuallyDrop;
22use std::{marker::PhantomData, slice};
23
24/// A type alias to keep compatibility. See [`DBRawIteratorWithThreadMode`] for details
25pub type DBRawIterator<'a> = DBRawIteratorWithThreadMode<'a, DB>;
26
27/// A low-level iterator over a database or column family, created by [`DB::raw_iterator`]
28/// and other `raw_iterator_*` methods.
29///
30/// This iterator replicates RocksDB's API. It should provide better
31/// performance and more features than [`DBIteratorWithThreadMode`], which is a standard
32/// Rust [`std::iter::Iterator`].
33///
34/// ```
35/// use rust_rocksdb::{DB, Options};
36///
37/// let tempdir = tempfile::Builder::new()
38/// .prefix("_path_for_rocksdb_storage4")
39/// .tempdir()
40/// .expect("Failed to create temporary path for the _path_for_rocksdb_storage4.");
41/// let path = tempdir.path();
42/// {
43/// let db = DB::open_default(path).unwrap();
44/// let mut iter = db.raw_iterator();
45///
46/// // Forwards iteration
47/// iter.seek_to_first();
48/// while iter.valid() {
49/// println!("Saw {:?} {:?}", iter.key(), iter.value());
50/// iter.next();
51/// }
52///
53/// // Reverse iteration
54/// iter.seek_to_last();
55/// while iter.valid() {
56/// println!("Saw {:?} {:?}", iter.key(), iter.value());
57/// iter.prev();
58/// }
59///
60/// // Seeking
61/// iter.seek(b"my key");
62/// while iter.valid() {
63/// println!("Saw {:?} {:?}", iter.key(), iter.value());
64/// iter.next();
65/// }
66///
67/// // Reverse iteration from key
68/// // Note, use seek_for_prev when reversing because if this key doesn't exist,
69/// // this will make the iterator start from the previous key rather than the next.
70/// iter.seek_for_prev(b"my key");
71/// while iter.valid() {
72/// println!("Saw {:?} {:?}", iter.key(), iter.value());
73/// iter.prev();
74/// }
75/// }
76/// let _ = DB::destroy(&Options::default(), path);
77/// ```
78pub struct DBRawIteratorWithThreadMode<'a, D: DBAccess> {
79 inner: std::ptr::NonNull<ffi::rocksdb_iterator_t>,
80
81 /// When iterate_lower_bound or iterate_upper_bound are set, the inner
82 /// C iterator keeps a pointer to the upper bound inside `_readopts`.
83 /// Storing this makes sure the upper bound is always alive when the
84 /// iterator is being used.
85 ///
86 /// And yes, we need to store the entire ReadOptions structure since C++
87 /// ReadOptions keep reference to C rocksdb_readoptions_t wrapper which
88 /// point to vectors we own. See issue #660.
89 readopts: ReadOptions,
90
91 db: PhantomData<&'a D>,
92}
93
94impl<'a, D: DBAccess> DBRawIteratorWithThreadMode<'a, D> {
95 pub(crate) fn new(db: &D, readopts: ReadOptions) -> Self {
96 let inner = unsafe { db.create_iterator(&readopts) };
97 Self::from_inner(inner, readopts)
98 }
99
100 pub(crate) fn new_cf(
101 db: &'a D,
102 cf_handle: *mut ffi::rocksdb_column_family_handle_t,
103 readopts: ReadOptions,
104 ) -> Self {
105 let inner = unsafe { db.create_iterator_cf(cf_handle, &readopts) };
106 Self::from_inner(inner, readopts)
107 }
108
109 pub(crate) fn from_inner(inner: *mut ffi::rocksdb_iterator_t, readopts: ReadOptions) -> Self {
110 // This unwrap will never fail since rocksdb_create_iterator and
111 // rocksdb_create_iterator_cf functions always return non-null. They
112 // use new and deference the result so any nulls would end up with SIGSEGV
113 // there and we would have a bigger issue.
114 let inner = std::ptr::NonNull::new(inner).unwrap();
115 Self {
116 inner,
117 readopts,
118 db: PhantomData,
119 }
120 }
121
122 pub(crate) fn into_inner(self) -> (std::ptr::NonNull<ffi::rocksdb_iterator_t>, ReadOptions) {
123 let value = ManuallyDrop::new(self);
124 // SAFETY: value won't be used beyond this point
125 let inner = unsafe { std::ptr::read(&raw const value.inner) };
126 let readopts = unsafe { std::ptr::read(&raw const value.readopts) };
127
128 (inner, readopts)
129 }
130
131 /// Returns `true` if the iterator is valid. An iterator is invalidated when
132 /// it reaches the end of its defined range, or when it encounters an error.
133 ///
134 /// To check whether the iterator encountered an error after `valid` has
135 /// returned `false`, use the [`status`](DBRawIteratorWithThreadMode::status) method. `status` will never
136 /// return an error when `valid` is `true`.
137 pub fn valid(&self) -> bool {
138 unsafe { ffi::rocksdb_iter_valid(self.inner.as_ptr()) != 0 }
139 }
140
141 /// Returns an error `Result` if the iterator has encountered an error
142 /// during operation. When an error is encountered, the iterator is
143 /// invalidated and [`valid`](DBRawIteratorWithThreadMode::valid) will return `false` when called.
144 ///
145 /// Performing a seek will discard the current status.
146 pub fn status(&self) -> Result<(), Error> {
147 unsafe {
148 ffi_try!(ffi::rocksdb_iter_get_error(self.inner.as_ptr()));
149 }
150 Ok(())
151 }
152
153 /// Refreshes the iterator to represent the latest state of the DB.
154 /// The iterator is invalidated after this call and must be re-sought
155 /// before use.
156 ///
157 /// If the iterator was created with a snapshot, the refreshed iterator
158 /// will no longer use that snapshot and will instead read the latest
159 /// DB state. The snapshot itself is not released; it remains valid and
160 /// will be released when the owning [`crate::SnapshotWithThreadMode`] is dropped.
161 pub fn refresh(&mut self) -> Result<(), Error> {
162 unsafe {
163 ffi_try!(ffi::rocksdb_iter_refresh(self.inner.as_ptr()));
164 }
165 Ok(())
166 }
167
168 /// Seeks to the first key in the database.
169 ///
170 /// # Examples
171 ///
172 /// ```rust
173 /// use rust_rocksdb::{DB, Options};
174 ///
175 /// let tempdir = tempfile::Builder::new()
176 /// .prefix("_path_for_rocksdb_storage5")
177 /// .tempdir()
178 /// .expect("Failed to create temporary path for the _path_for_rocksdb_storage5.");
179 /// let path = tempdir.path();
180 /// {
181 /// let db = DB::open_default(path).unwrap();
182 /// let mut iter = db.raw_iterator();
183 ///
184 /// // Iterate all keys from the start in lexicographic order
185 /// iter.seek_to_first();
186 ///
187 /// while iter.valid() {
188 /// println!("{:?} {:?}", iter.key(), iter.value());
189 /// iter.next();
190 /// }
191 ///
192 /// // Read just the first key
193 /// iter.seek_to_first();
194 ///
195 /// if iter.valid() {
196 /// println!("{:?} {:?}", iter.key(), iter.value());
197 /// } else {
198 /// // There are no keys in the database
199 /// }
200 /// }
201 /// let _ = DB::destroy(&Options::default(), path);
202 /// ```
203 pub fn seek_to_first(&mut self) {
204 unsafe {
205 ffi::rocksdb_iter_seek_to_first(self.inner.as_ptr());
206 }
207 }
208
209 /// Seeks to the last key in the database.
210 ///
211 /// # Examples
212 ///
213 /// ```rust
214 /// use rust_rocksdb::{DB, Options};
215 ///
216 /// let tempdir = tempfile::Builder::new()
217 /// .prefix("_path_for_rocksdb_storage6")
218 /// .tempdir()
219 /// .expect("Failed to create temporary path for the _path_for_rocksdb_storage6.");
220 /// let path = tempdir.path();
221 /// {
222 /// let db = DB::open_default(path).unwrap();
223 /// let mut iter = db.raw_iterator();
224 ///
225 /// // Iterate all keys from the end in reverse lexicographic order
226 /// iter.seek_to_last();
227 ///
228 /// while iter.valid() {
229 /// println!("{:?} {:?}", iter.key(), iter.value());
230 /// iter.prev();
231 /// }
232 ///
233 /// // Read just the last key
234 /// iter.seek_to_last();
235 ///
236 /// if iter.valid() {
237 /// println!("{:?} {:?}", iter.key(), iter.value());
238 /// } else {
239 /// // There are no keys in the database
240 /// }
241 /// }
242 /// let _ = DB::destroy(&Options::default(), path);
243 /// ```
244 pub fn seek_to_last(&mut self) {
245 unsafe {
246 ffi::rocksdb_iter_seek_to_last(self.inner.as_ptr());
247 }
248 }
249
250 /// Seeks to the specified key or the first key that lexicographically follows it.
251 ///
252 /// This method will attempt to seek to the specified key. If that key does not exist, it will
253 /// find and seek to the key that lexicographically follows it instead.
254 ///
255 /// # Examples
256 ///
257 /// ```rust
258 /// use rust_rocksdb::{DB, Options};
259 ///
260 /// let tempdir = tempfile::Builder::new()
261 /// .prefix("_path_for_rocksdb_storage7")
262 /// .tempdir()
263 /// .expect("Failed to create temporary path for the _path_for_rocksdb_storage7.");
264 /// let path = tempdir.path();
265 /// {
266 /// let db = DB::open_default(path).unwrap();
267 /// let mut iter = db.raw_iterator();
268 ///
269 /// // Read the first key that starts with 'a'
270 /// iter.seek(b"a");
271 ///
272 /// if iter.valid() {
273 /// println!("{:?} {:?}", iter.key(), iter.value());
274 /// } else {
275 /// // There are no keys in the database
276 /// }
277 /// }
278 /// let _ = DB::destroy(&Options::default(), path);
279 /// ```
280 pub fn seek<K: AsRef<[u8]>>(&mut self, key: K) {
281 let key = key.as_ref();
282
283 unsafe {
284 ffi::rocksdb_iter_seek(
285 self.inner.as_ptr(),
286 key.as_ptr() as *const c_char,
287 key.len() as size_t,
288 );
289 }
290 }
291
292 /// Seeks to the specified key, or the first key that lexicographically precedes it.
293 ///
294 /// Like ``.seek()`` this method will attempt to seek to the specified key.
295 /// The difference with ``.seek()`` is that if the specified key do not exist, this method will
296 /// seek to key that lexicographically precedes it instead.
297 ///
298 /// # Examples
299 ///
300 /// ```rust
301 /// use rust_rocksdb::{DB, Options};
302 ///
303 /// let tempdir = tempfile::Builder::new()
304 /// .prefix("_path_for_rocksdb_storage8")
305 /// .tempdir()
306 /// .expect("Failed to create temporary path for the _path_for_rocksdb_storage8.");
307 /// let path = tempdir.path();
308 /// {
309 /// let db = DB::open_default(path).unwrap();
310 /// let mut iter = db.raw_iterator();
311 ///
312 /// // Read the last key that starts with 'a'
313 /// iter.seek_for_prev(b"b");
314 ///
315 /// if iter.valid() {
316 /// println!("{:?} {:?}", iter.key(), iter.value());
317 /// } else {
318 /// // There are no keys in the database
319 /// }
320 /// }
321 /// let _ = DB::destroy(&Options::default(), path);
322 /// ```
323 pub fn seek_for_prev<K: AsRef<[u8]>>(&mut self, key: K) {
324 let key = key.as_ref();
325
326 unsafe {
327 ffi::rocksdb_iter_seek_for_prev(
328 self.inner.as_ptr(),
329 key.as_ptr() as *const c_char,
330 key.len() as size_t,
331 );
332 }
333 }
334
335 /// Seeks to the next key.
336 pub fn next(&mut self) {
337 if self.valid() {
338 unsafe {
339 ffi::rocksdb_iter_next(self.inner.as_ptr());
340 }
341 }
342 }
343
344 /// Seeks to the previous key.
345 pub fn prev(&mut self) {
346 if self.valid() {
347 unsafe {
348 ffi::rocksdb_iter_prev(self.inner.as_ptr());
349 }
350 }
351 }
352
353 /// Returns a slice of the current key.
354 pub fn key(&self) -> Option<&[u8]> {
355 if self.valid() {
356 // SAFETY: We just checked that the iterator is valid.
357 Some(unsafe { self.key_impl() })
358 } else {
359 None
360 }
361 }
362
363 /// Returns a slice of the current value.
364 pub fn value(&self) -> Option<&[u8]> {
365 if self.valid() {
366 // SAFETY: We just checked that the iterator is valid.
367 Some(unsafe { self.value_impl() })
368 } else {
369 None
370 }
371 }
372
373 /// Returns pair with slice of the current key and current value.
374 pub fn item(&self) -> Option<(&[u8], &[u8])> {
375 if self.valid() {
376 // SAFETY: We just checked that the iterator is valid.
377 Some(unsafe { (self.key_impl(), self.value_impl()) })
378 } else {
379 None
380 }
381 }
382
383 /// Returns a slice of the current key.
384 ///
385 /// # Safety
386 ///
387 /// The iterator must be valid (i.e., `valid()` returns true). Calling this
388 /// method when the iterator is invalid is undefined behavior, as RocksDB
389 /// may return an invalid pointer.
390 ///
391 /// Uses `rocksdb_iter_key_slice` which returns a `rocksdb_slice_t` by value,
392 /// avoiding the overhead of output parameters compared to `rocksdb_iter_key`.
393 unsafe fn key_impl(&self) -> &[u8] {
394 unsafe {
395 let slice = ffi::rocksdb_iter_key_slice(self.inner.as_ptr());
396 slice::from_raw_parts(slice.data as *const c_uchar, slice.size)
397 }
398 }
399
400 /// Returns a slice of the current value.
401 ///
402 /// # Safety
403 ///
404 /// The iterator must be valid (i.e., `valid()` returns true). Calling this
405 /// method when the iterator is invalid is undefined behavior, as RocksDB
406 /// may return an invalid pointer.
407 ///
408 /// Uses `rocksdb_iter_value_slice` which returns a `rocksdb_slice_t` by value,
409 /// avoiding the overhead of output parameters compared to `rocksdb_iter_value`.
410 unsafe fn value_impl(&self) -> &[u8] {
411 unsafe {
412 let slice = ffi::rocksdb_iter_value_slice(self.inner.as_ptr());
413 slice::from_raw_parts(slice.data as *const c_uchar, slice.size)
414 }
415 }
416
417 /// Returns a slice of the current entry's timestamp.
418 pub fn timestamp(&self) -> Option<&[u8]> {
419 if self.valid() {
420 // SAFETY: We just checked that the iterator is valid.
421 Some(unsafe { self.timestamp_unchecked() })
422 } else {
423 None
424 }
425 }
426
427 /// Returns the timestamp of the current entry without checking iterator validity.
428 ///
429 /// # Safety
430 ///
431 /// The iterator must be valid (i.e., `valid()` returns true). Calling this
432 /// method when the iterator is invalid is undefined behavior, as RocksDB
433 /// may return an invalid pointer.
434 ///
435 /// Uses `rocksdb_iter_timestamp_slice` which returns a `rocksdb_slice_t` by value,
436 /// avoiding the overhead of output parameters compared to `rocksdb_iter_timestamp`.
437 pub unsafe fn timestamp_unchecked(&self) -> &[u8] {
438 unsafe {
439 let slice = ffi::rocksdb_iter_timestamp_slice(self.inner.as_ptr());
440 if slice.size == 0 {
441 return &[];
442 }
443 slice::from_raw_parts(slice.data as *const c_uchar, slice.size)
444 }
445 }
446}
447
448impl<D: DBAccess> Drop for DBRawIteratorWithThreadMode<'_, D> {
449 fn drop(&mut self) {
450 unsafe {
451 ffi::rocksdb_iter_destroy(self.inner.as_ptr());
452 }
453 }
454}
455
456unsafe impl<D: DBAccess> Send for DBRawIteratorWithThreadMode<'_, D> {}
457unsafe impl<D: DBAccess> Sync for DBRawIteratorWithThreadMode<'_, D> {}
458
459/// A type alias to keep compatibility. See [`DBIteratorWithThreadMode`] for details
460pub type DBIterator<'a> = DBIteratorWithThreadMode<'a, DB>;
461
462/// A standard Rust [`Iterator`] over a database or column family.
463///
464/// As an alternative, [`DBRawIteratorWithThreadMode`] is a low level wrapper around
465/// RocksDB's API, which can provide better performance and more features.
466///
467/// ```
468/// use rust_rocksdb::{DB, Direction, IteratorMode, Options};
469///
470/// let tempdir = tempfile::Builder::new()
471/// .prefix("_path_for_rocksdb_storage2")
472/// .tempdir()
473/// .expect("Failed to create temporary path for the _path_for_rocksdb_storage2.");
474/// let path = tempdir.path();
475/// {
476/// let db = DB::open_default(path).unwrap();
477/// let mut iter = db.iterator(IteratorMode::Start); // Always iterates forward
478/// for item in iter {
479/// let (key, value) = item.unwrap();
480/// println!("Saw {:?} {:?}", key, value);
481/// }
482/// iter = db.iterator(IteratorMode::End); // Always iterates backward
483/// for item in iter {
484/// let (key, value) = item.unwrap();
485/// println!("Saw {:?} {:?}", key, value);
486/// }
487/// iter = db.iterator(IteratorMode::From(b"my key", Direction::Forward)); // From a key in Direction::{forward,reverse}
488/// for item in iter {
489/// let (key, value) = item.unwrap();
490/// println!("Saw {:?} {:?}", key, value);
491/// }
492///
493/// // You can seek with an existing Iterator instance, too
494/// iter = db.iterator(IteratorMode::Start);
495/// iter.set_mode(IteratorMode::From(b"another key", Direction::Reverse));
496/// for item in iter {
497/// let (key, value) = item.unwrap();
498/// println!("Saw {:?} {:?}", key, value);
499/// }
500/// }
501/// let _ = DB::destroy(&Options::default(), path);
502/// ```
503///
504/// An iterator must not outlive the `DB` it iterates over:
505///
506/// ```compile_fail,E0597
507/// use rust_rocksdb::{IteratorMode, DB};
508///
509/// let _iter = {
510/// let db = DB::open_default("foo").unwrap();
511/// db.iterator(IteratorMode::Start)
512/// };
513/// ```
514pub struct DBIteratorWithThreadMode<'a, D: DBAccess> {
515 raw: DBRawIteratorWithThreadMode<'a, D>,
516 direction: Direction,
517 done: bool,
518}
519
520#[derive(Copy, Clone)]
521pub enum Direction {
522 Forward,
523 Reverse,
524}
525
526pub type KVBytes = (Box<[u8]>, Box<[u8]>);
527
528#[derive(Copy, Clone)]
529pub enum IteratorMode<'a> {
530 Start,
531 End,
532 From(&'a [u8], Direction),
533}
534
535impl<'a, D: DBAccess> DBIteratorWithThreadMode<'a, D> {
536 pub(crate) fn new(db: &D, readopts: ReadOptions, mode: IteratorMode) -> Self {
537 Self::from_raw(DBRawIteratorWithThreadMode::new(db, readopts), mode)
538 }
539
540 pub(crate) fn new_cf(
541 db: &'a D,
542 cf_handle: *mut ffi::rocksdb_column_family_handle_t,
543 readopts: ReadOptions,
544 mode: IteratorMode,
545 ) -> Self {
546 Self::from_raw(
547 DBRawIteratorWithThreadMode::new_cf(db, cf_handle, readopts),
548 mode,
549 )
550 }
551
552 fn from_raw(raw: DBRawIteratorWithThreadMode<'a, D>, mode: IteratorMode) -> Self {
553 let mut rv = DBIteratorWithThreadMode {
554 raw,
555 direction: Direction::Forward, // blown away by set_mode()
556 done: false,
557 };
558 rv.set_mode(mode);
559 rv
560 }
561
562 pub fn set_mode(&mut self, mode: IteratorMode) {
563 self.done = false;
564 self.direction = match mode {
565 IteratorMode::Start => {
566 self.raw.seek_to_first();
567 Direction::Forward
568 }
569 IteratorMode::End => {
570 self.raw.seek_to_last();
571 Direction::Reverse
572 }
573 IteratorMode::From(key, Direction::Forward) => {
574 self.raw.seek(key);
575 Direction::Forward
576 }
577 IteratorMode::From(key, Direction::Reverse) => {
578 self.raw.seek_for_prev(key);
579 Direction::Reverse
580 }
581 };
582 }
583
584 /// Refreshes the iterator, then re-seeks using the given mode.
585 ///
586 /// After a refresh the underlying iterator is invalidated, so a mode
587 /// must be provided to reposition it.
588 pub fn refresh(&mut self, mode: IteratorMode) -> Result<(), Error> {
589 self.raw.refresh()?;
590 self.set_mode(mode);
591 Ok(())
592 }
593}
594
595impl<D: DBAccess> Iterator for DBIteratorWithThreadMode<'_, D> {
596 type Item = Result<KVBytes, Error>;
597
598 fn next(&mut self) -> Option<Result<KVBytes, Error>> {
599 if self.done {
600 None
601 } else if let Some((key, value)) = self.raw.item() {
602 let item = (Box::from(key), Box::from(value));
603 match self.direction {
604 Direction::Forward => self.raw.next(),
605 Direction::Reverse => self.raw.prev(),
606 }
607 Some(Ok(item))
608 } else {
609 self.done = true;
610 self.raw.status().err().map(Result::Err)
611 }
612 }
613}
614
615impl<D: DBAccess> std::iter::FusedIterator for DBIteratorWithThreadMode<'_, D> {}
616
617impl<'a, D: DBAccess> Into<DBRawIteratorWithThreadMode<'a, D>> for DBIteratorWithThreadMode<'a, D> {
618 fn into(self) -> DBRawIteratorWithThreadMode<'a, D> {
619 self.raw
620 }
621}
622
623/// Iterates the batches of writes since a given sequence number.
624///
625/// `DBWALIterator` is returned by `DB::get_updates_since()` and will return the
626/// batches of write operations that have occurred since a given sequence number
627/// (see `DB::latest_sequence_number()`). This iterator cannot be constructed by
628/// the application.
629///
630/// The iterator item type is a tuple of (`u64`, `WriteBatch`) where the first
631/// value is the sequence number of the associated write batch.
632///
633pub struct DBWALIterator {
634 pub(crate) inner: *mut ffi::rocksdb_wal_iterator_t,
635 pub(crate) start_seq_number: u64,
636}
637
638impl DBWALIterator {
639 /// Returns `true` if the iterator is valid. An iterator is invalidated when
640 /// it reaches the end of its defined range, or when it encounters an error.
641 ///
642 /// To check whether the iterator encountered an error after `valid` has
643 /// returned `false`, use the [`status`](DBWALIterator::status) method.
644 /// `status` will never return an error when `valid` is `true`.
645 pub fn valid(&self) -> bool {
646 unsafe { ffi::rocksdb_wal_iter_valid(self.inner) != 0 }
647 }
648
649 /// Returns an error `Result` if the iterator has encountered an error
650 /// during operation. When an error is encountered, the iterator is
651 /// invalidated and [`valid`](DBWALIterator::valid) will return `false` when
652 /// called.
653 pub fn status(&self) -> Result<(), Error> {
654 unsafe {
655 ffi_try!(ffi::rocksdb_wal_iter_status(self.inner));
656 }
657 Ok(())
658 }
659}
660
661impl Iterator for DBWALIterator {
662 type Item = Result<(u64, WriteBatch), Error>;
663
664 fn next(&mut self) -> Option<Self::Item> {
665 if !self.valid() {
666 return None;
667 }
668
669 let mut seq: u64 = 0;
670 let mut batch = WriteBatch {
671 inner: unsafe { ffi::rocksdb_wal_iter_get_batch(self.inner, &raw mut seq) },
672 };
673
674 // if the initial sequence number is what was requested we skip it to
675 // only provide changes *after* it
676 while seq <= self.start_seq_number {
677 unsafe {
678 ffi::rocksdb_wal_iter_next(self.inner);
679 }
680
681 if !self.valid() {
682 return None;
683 }
684
685 // this drops which in turn frees the skipped batch
686 batch = WriteBatch {
687 inner: unsafe { ffi::rocksdb_wal_iter_get_batch(self.inner, &raw mut seq) },
688 };
689 }
690
691 if !self.valid() {
692 return self.status().err().map(Result::Err);
693 }
694
695 // Seek to the next write batch.
696 // Note that WriteBatches live independently of the WAL iterator so this is safe to do
697 unsafe {
698 ffi::rocksdb_wal_iter_next(self.inner);
699 }
700
701 Some(Ok((seq, batch)))
702 }
703}
704
705impl Drop for DBWALIterator {
706 fn drop(&mut self) {
707 unsafe {
708 ffi::rocksdb_wal_iter_destroy(self.inner);
709 }
710 }
711}