Debian Codegraph @

src/iterator/range.rs

raw
1 use std::borrow::Cow;
2 use std::marker;
3 use std::ops::Bound;
4
5 use types::LazyDecode;
6
7 use crate::cursor::MoveOperation;
8 use crate::iteration_method::{IterationMethod, MoveBetweenKeys, MoveThroughDuplicateValues};
9 use crate::*;
10
11 fn move_on_range_end<'txn>(
12 cursor: &mut RoCursor<'txn>,
13 end_bound: &Bound<Vec<u8>>,
14 ) -> Result<Option<(&'txn [u8], &'txn [u8])>> {
15 match end_bound {
16 Bound::Included(end) => match cursor.move_on_key_greater_than_or_equal_to(end) {
17 Ok(Some((key, data))) if key == &end[..] => Ok(Some((key, data))),
18 Ok(_) => cursor.move_on_prev(MoveOperation::NoDup),
19 Err(e) => Err(e),
20 },
21 Bound::Excluded(end) => cursor
22 .move_on_key_greater_than_or_equal_to(end)
23 .and_then(|_| cursor.move_on_prev(MoveOperation::NoDup)),
24 Bound::Unbounded => cursor.move_on_last(MoveOperation::NoDup),
25 }
26 }
27
28 fn move_on_range_start<'txn>(
29 cursor: &mut RoCursor<'txn>,
30 start_bound: &mut Bound<Vec<u8>>,
31 ) -> Result<Option<(&'txn [u8], &'txn [u8])>> {
32 match start_bound {
33 Bound::Included(start) => cursor.move_on_key_greater_than_or_equal_to(start),
34 Bound::Excluded(start) => match cursor.move_on_key_greater_than_or_equal_to(start)? {
35 Some((key, _)) if key == start => cursor.move_on_next(MoveOperation::NoDup),
36 result => Ok(result),
37 },
38 Bound::Unbounded => cursor.move_on_first(MoveOperation::NoDup),
39 }
40 }
41
42 /// A read-only range iterator structure.
43 pub struct RoRange<'txn, KC, DC, C = DefaultComparator, IM = MoveThroughDuplicateValues> {
44 cursor: RoCursor<'txn>,
45 move_on_start: bool,
46 start_bound: Bound<Vec<u8>>,
47 end_bound: Bound<Vec<u8>>,
48 _phantom: marker::PhantomData<(KC, DC, C, IM)>,
49 }
50
51 impl<'txn, KC, DC, C, IM> RoRange<'txn, KC, DC, C, IM> {
52 pub(crate) fn new(
53 cursor: RoCursor<'txn>,
54 start_bound: Bound<Vec<u8>>,
55 end_bound: Bound<Vec<u8>>,
56 ) -> RoRange<'txn, KC, DC, C, IM> {
57 RoRange {
58 cursor,
59 move_on_start: true,
60 start_bound,
61 end_bound,
62 _phantom: marker::PhantomData,
63 }
64 }
65
66 /// Move on the first value of keys, ignoring duplicate values.
67 ///
68 /// For more info, see [`RoIter::move_between_keys`].
69 pub fn move_between_keys(self) -> RoRange<'txn, KC, DC, C, MoveBetweenKeys> {
70 RoRange {
71 cursor: self.cursor,
72 move_on_start: self.move_on_start,
73 start_bound: self.start_bound,
74 end_bound: self.end_bound,
75 _phantom: marker::PhantomData,
76 }
77 }
78
79 /// Move through key/values entries and output duplicate values.
80 ///
81 /// For more info, see [`RoIter::move_through_duplicate_values`].
82 pub fn move_through_duplicate_values(
83 self,
84 ) -> RoRange<'txn, KC, DC, C, MoveThroughDuplicateValues> {
85 RoRange {
86 cursor: self.cursor,
87 move_on_start: self.move_on_start,
88 start_bound: self.start_bound,
89 end_bound: self.end_bound,
90 _phantom: marker::PhantomData,
91 }
92 }
93
94 /// Change the codec types of this iterator, specifying the codecs.
95 pub fn remap_types<KC2, DC2>(self) -> RoRange<'txn, KC2, DC2, C, IM> {
96 RoRange {
97 cursor: self.cursor,
98 move_on_start: self.move_on_start,
99 start_bound: self.start_bound,
100 end_bound: self.end_bound,
101 _phantom: marker::PhantomData,
102 }
103 }
104
105 /// Change the key codec type of this iterator, specifying the new codec.
106 pub fn remap_key_type<KC2>(self) -> RoRange<'txn, KC2, DC, C, IM> {
107 self.remap_types::<KC2, DC>()
108 }
109
110 /// Change the data codec type of this iterator, specifying the new codec.
111 pub fn remap_data_type<DC2>(self) -> RoRange<'txn, KC, DC2, C, IM> {
112 self.remap_types::<KC, DC2>()
113 }
114
115 /// Wrap the data bytes into a lazy decoder.
116 pub fn lazily_decode_data(self) -> RoRange<'txn, KC, LazyDecode<DC>, C, IM> {
117 self.remap_types::<KC, LazyDecode<DC>>()
118 }
119 }
120
121 impl<'txn, KC, DC, C, IM> Iterator for RoRange<'txn, KC, DC, C, IM>
122 where
123 KC: BytesDecode<'txn>,
124 DC: BytesDecode<'txn>,
125 IM: IterationMethod,
126 C: Comparator,
127 {
128 type Item = Result<(KC::DItem, DC::DItem)>;
129
130 fn next(&mut self) -> Option<Self::Item> {
131 let result = if self.move_on_start {
132 self.move_on_start = false;
133 move_on_range_start(&mut self.cursor, &mut self.start_bound)
134 } else {
135 self.cursor.move_on_next(IM::MOVE_OPERATION)
136 };
137
138 match result {
139 Ok(Some((key, data))) => {
140 let must_be_returned = match &self.end_bound {
141 Bound::Included(end) => C::compare(key, end).is_le(),
142 Bound::Excluded(end) => C::compare(key, end).is_lt(),
143 Bound::Unbounded => true,
144 };
145
146 if must_be_returned {
147 match (KC::bytes_decode(key), DC::bytes_decode(data)) {
148 (Ok(key), Ok(data)) => Some(Ok((key, data))),
149 (Err(e), _) | (_, Err(e)) => Some(Err(Error::Decoding(e))),
150 }
151 } else {
152 None
153 }
154 }
155 Ok(None) => None,
156 Err(e) => Some(Err(e)),
157 }
158 }
159
160 fn last(mut self) -> Option<Self::Item> {
161 let result = if self.move_on_start {
162 move_on_range_end(&mut self.cursor, &self.end_bound)
163 } else {
164 match (self.cursor.current(), move_on_range_end(&mut self.cursor, &self.end_bound)) {
165 (Ok(Some((ckey, _))), Ok(Some((key, data)))) if C::compare(ckey, key).is_ne() => {
166 Ok(Some((key, data)))
167 }
168 (Ok(_), Ok(_)) => Ok(None),
169 (Err(e), _) | (_, Err(e)) => Err(e),
170 }
171 };
172
173 match result {
174 Ok(Some((key, data))) => {
175 let must_be_returned = match &self.start_bound {
176 Bound::Included(start) => C::compare(key, start).is_ge(),
177 Bound::Excluded(start) => C::compare(key, start).is_gt(),
178 Bound::Unbounded => true,
179 };
180
181 if must_be_returned {
182 match (KC::bytes_decode(key), DC::bytes_decode(data)) {
183 (Ok(key), Ok(data)) => Some(Ok((key, data))),
184 (Err(e), _) | (_, Err(e)) => Some(Err(Error::Decoding(e))),
185 }
186 } else {
187 None
188 }
189 }
190 Ok(None) => None,
191 Err(e) => Some(Err(e)),
192 }
193 }
194 }
195
196 impl<KC, DC, C, IM> fmt::Debug for RoRange<'_, KC, DC, C, IM> {
197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198 f.debug_struct("RoRange").finish()
199 }
200 }
201
202 /// A read-write range iterator structure.
203 pub struct RwRange<'txn, KC, DC, C = DefaultComparator, IM = MoveThroughDuplicateValues> {
204 cursor: RwCursor<'txn>,
205 move_on_start: bool,
206 start_bound: Bound<Vec<u8>>,
207 end_bound: Bound<Vec<u8>>,
208 _phantom: marker::PhantomData<(KC, DC, C, IM)>,
209 }
210
211 impl<'txn, KC, DC, C, IM> RwRange<'txn, KC, DC, C, IM> {
212 pub(crate) fn new(
213 cursor: RwCursor<'txn>,
214 start_bound: Bound<Vec<u8>>,
215 end_bound: Bound<Vec<u8>>,
216 ) -> RwRange<'txn, KC, DC, C, IM> {
217 RwRange {
218 cursor,
219 move_on_start: true,
220 start_bound,
221 end_bound,
222 _phantom: marker::PhantomData,
223 }
224 }
225
226 /// Delete the entry the cursor is currently pointing to.
227 ///
228 /// Returns `true` if the entry was successfully deleted.
229 ///
230 /// # Safety
231 ///
232 /// It is _[undefined behavior]_ to keep a reference of a value from this database
233 /// while modifying it.
234 ///
235 /// > [Values returned from the database are valid only until a subsequent update operation,
236 /// > or the end of the transaction.](http://www.lmdb.tech/doc/group__mdb.html#structMDB__val)
237 ///
238 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
239 pub unsafe fn del_current(&mut self) -> Result<bool> {
240 self.cursor.del_current()
241 }
242
243 /// Write a new value to the current entry.
244 ///
245 /// The given key **must** be equal to the one this cursor is pointing otherwise the database
246 /// can be put into an inconsistent state.
247 ///
248 /// Returns `true` if the entry was successfully written.
249 ///
250 /// > This is intended to be used when the new data is the same size as the old.
251 /// > Otherwise it will simply perform a delete of the old record followed by an insert.
252 ///
253 /// # Safety
254 ///
255 /// It is _[undefined behavior]_ to keep a reference of a value from this database while
256 /// modifying it, so you can't use the key/value that comes from the cursor to feed
257 /// this function.
258 ///
259 /// In other words: Transform the key and value that you borrow from this database into an owned
260 /// version of them (e.g. `&str` into `String`).
261 ///
262 /// > [Values returned from the database are valid only until a subsequent update operation,
263 /// > or the end of the transaction.](http://www.lmdb.tech/doc/group__mdb.html#structMDB__val)
264 ///
265 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
266 pub unsafe fn put_current<'a>(
267 &mut self,
268 key: &'a KC::EItem,
269 data: &'a DC::EItem,
270 ) -> Result<bool>
271 where
272 KC: BytesEncode<'a>,
273 DC: BytesEncode<'a>,
274 {
275 let key_bytes: Cow<[u8]> = KC::bytes_encode(key).map_err(Error::Encoding)?;
276 let data_bytes: Cow<[u8]> = DC::bytes_encode(data).map_err(Error::Encoding)?;
277 self.cursor.put_current(&key_bytes, &data_bytes)
278 }
279
280 /// Write a new value to the current entry. The entry is written with the specified flags.
281 ///
282 /// The given key **must** be equal to the one this cursor is pointing otherwise the database
283 /// can be put into an inconsistent state.
284 ///
285 /// Returns `true` if the entry was successfully written.
286 ///
287 /// > This is intended to be used when the new data is the same size as the old.
288 /// > Otherwise it will simply perform a delete of the old record followed by an insert.
289 ///
290 /// # Safety
291 ///
292 /// Please read the safety notes of the [`RwRange::put_current`] method.
293 pub unsafe fn put_current_reserved_with_flags<'a, F>(
294 &mut self,
295 flags: PutFlags,
296 key: &'a KC::EItem,
297 data_size: usize,
298 write_func: F,
299 ) -> Result<bool>
300 where
301 KC: BytesEncode<'a>,
302 F: FnOnce(&mut ReservedSpace) -> io::Result<()>,
303 {
304 let key_bytes: Cow<[u8]> = KC::bytes_encode(key).map_err(Error::Encoding)?;
305 self.cursor.put_current_reserved_with_flags(flags, &key_bytes, data_size, write_func)
306 }
307
308 /// Insert a key-value pair in this database. The entry is written with the specified flags and data codec.
309 ///
310 /// For more info, see [`RwIter::put_current_with_options`].
311 ///
312 /// # Safety
313 ///
314 /// It is _[undefined behavior]_ to keep a reference of a value from this database while
315 /// modifying it, so you can't use the key/value that comes from the cursor to feed
316 /// this function.
317 ///
318 /// In other words: Transform the key and value that you borrow from this database into an owned
319 /// version of them (e.g. `&str` into `String`).
320 ///
321 /// > [Values returned from the database are valid only until a subsequent update operation,
322 /// > or the end of the transaction.](http://www.lmdb.tech/doc/group__mdb.html#structMDB__val)
323 ///
324 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
325 pub unsafe fn put_current_with_options<'a, NDC>(
326 &mut self,
327 flags: PutFlags,
328 key: &'a KC::EItem,
329 data: &'a NDC::EItem,
330 ) -> Result<()>
331 where
332 KC: BytesEncode<'a>,
333 NDC: BytesEncode<'a>,
334 {
335 let key_bytes: Cow<[u8]> = KC::bytes_encode(key).map_err(Error::Encoding)?;
336 let data_bytes: Cow<[u8]> = NDC::bytes_encode(data).map_err(Error::Encoding)?;
337 self.cursor.put_current_with_flags(flags, &key_bytes, &data_bytes)
338 }
339
340 /// Move on the first value of keys, ignoring duplicate values.
341 ///
342 /// For more info, see [`RoIter::move_between_keys`].
343 pub fn move_between_keys(self) -> RwRange<'txn, KC, DC, C, MoveBetweenKeys> {
344 RwRange {
345 cursor: self.cursor,
346 move_on_start: self.move_on_start,
347 start_bound: self.start_bound,
348 end_bound: self.end_bound,
349 _phantom: marker::PhantomData,
350 }
351 }
352
353 /// Move through key/values entries and output duplicate values.
354 ///
355 /// For more info, see [`RoIter::move_through_duplicate_values`].
356 pub fn move_through_duplicate_values(
357 self,
358 ) -> RwRange<'txn, KC, DC, C, MoveThroughDuplicateValues> {
359 RwRange {
360 cursor: self.cursor,
361 move_on_start: self.move_on_start,
362 start_bound: self.start_bound,
363 end_bound: self.end_bound,
364 _phantom: marker::PhantomData,
365 }
366 }
367
368 /// Change the codec types of this iterator, specifying the codecs.
369 pub fn remap_types<KC2, DC2>(self) -> RwRange<'txn, KC2, DC2, C, IM> {
370 RwRange {
371 cursor: self.cursor,
372 move_on_start: self.move_on_start,
373 start_bound: self.start_bound,
374 end_bound: self.end_bound,
375 _phantom: marker::PhantomData,
376 }
377 }
378
379 /// Change the key codec type of this iterator, specifying the new codec.
380 pub fn remap_key_type<KC2>(self) -> RwRange<'txn, KC2, DC, C, IM> {
381 self.remap_types::<KC2, DC>()
382 }
383
384 /// Change the data codec type of this iterator, specifying the new codec.
385 pub fn remap_data_type<DC2>(self) -> RwRange<'txn, KC, DC2, C, IM> {
386 self.remap_types::<KC, DC2>()
387 }
388
389 /// Wrap the data bytes into a lazy decoder.
390 pub fn lazily_decode_data(self) -> RwRange<'txn, KC, LazyDecode<DC>, C, IM> {
391 self.remap_types::<KC, LazyDecode<DC>>()
392 }
393 }
394
395 impl<'txn, KC, DC, C, IM> Iterator for RwRange<'txn, KC, DC, C, IM>
396 where
397 KC: BytesDecode<'txn>,
398 DC: BytesDecode<'txn>,
399 IM: IterationMethod,
400 C: Comparator,
401 {
402 type Item = Result<(KC::DItem, DC::DItem)>;
403
404 fn next(&mut self) -> Option<Self::Item> {
405 let result = if self.move_on_start {
406 self.move_on_start = false;
407 move_on_range_start(&mut self.cursor, &mut self.start_bound)
408 } else {
409 self.cursor.move_on_next(IM::MOVE_OPERATION)
410 };
411
412 match result {
413 Ok(Some((key, data))) => {
414 let must_be_returned = match self.end_bound {
415 Bound::Included(ref end) => C::compare(key, end).is_le(),
416 Bound::Excluded(ref end) => C::compare(key, end).is_lt(),
417 Bound::Unbounded => true,
418 };
419
420 if must_be_returned {
421 match (KC::bytes_decode(key), DC::bytes_decode(data)) {
422 (Ok(key), Ok(data)) => Some(Ok((key, data))),
423 (Err(e), _) | (_, Err(e)) => Some(Err(Error::Decoding(e))),
424 }
425 } else {
426 None
427 }
428 }
429 Ok(None) => None,
430 Err(e) => Some(Err(e)),
431 }
432 }
433
434 fn last(mut self) -> Option<Self::Item> {
435 let result = if self.move_on_start {
436 move_on_range_end(&mut self.cursor, &self.end_bound)
437 } else {
438 match (self.cursor.current(), move_on_range_end(&mut self.cursor, &self.end_bound)) {
439 (Ok(Some((ckey, _))), Ok(Some((key, data)))) if C::compare(ckey, key).is_ne() => {
440 Ok(Some((key, data)))
441 }
442 (Ok(_), Ok(_)) => Ok(None),
443 (Err(e), _) | (_, Err(e)) => Err(e),
444 }
445 };
446
447 match result {
448 Ok(Some((key, data))) => {
449 let must_be_returned = match &self.start_bound {
450 Bound::Included(start) => C::compare(key, start).is_ge(),
451 Bound::Excluded(start) => C::compare(key, start).is_gt(),
452 Bound::Unbounded => true,
453 };
454
455 if must_be_returned {
456 match (KC::bytes_decode(key), DC::bytes_decode(data)) {
457 (Ok(key), Ok(data)) => Some(Ok((key, data))),
458 (Err(e), _) | (_, Err(e)) => Some(Err(Error::Decoding(e))),
459 }
460 } else {
461 None
462 }
463 }
464 Ok(None) => None,
465 Err(e) => Some(Err(e)),
466 }
467 }
468 }
469
470 impl<KC, DC, C, IM> fmt::Debug for RwRange<'_, KC, DC, C, IM> {
471 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472 f.debug_struct("RwRange").finish()
473 }
474 }
475
476 /// A reverse read-only range iterator structure.
477 pub struct RoRevRange<'txn, KC, DC, C = DefaultComparator, IM = MoveThroughDuplicateValues> {
478 cursor: RoCursor<'txn>,
479 move_on_end: bool,
480 start_bound: Bound<Vec<u8>>,
481 end_bound: Bound<Vec<u8>>,
482 _phantom: marker::PhantomData<(KC, DC, C, IM)>,
483 }
484
485 impl<'txn, KC, DC, C, IM> RoRevRange<'txn, KC, DC, C, IM> {
486 pub(crate) fn new(
487 cursor: RoCursor<'txn>,
488 start_bound: Bound<Vec<u8>>,
489 end_bound: Bound<Vec<u8>>,
490 ) -> RoRevRange<'txn, KC, DC, C, IM> {
491 RoRevRange {
492 cursor,
493 move_on_end: true,
494 start_bound,
495 end_bound,
496 _phantom: marker::PhantomData,
497 }
498 }
499
500 /// Move on the first value of keys, ignoring duplicate values.
501 ///
502 /// For more info, see [`RoIter::move_between_keys`].
503 pub fn move_between_keys(self) -> RoRevRange<'txn, KC, DC, C, MoveBetweenKeys> {
504 RoRevRange {
505 cursor: self.cursor,
506 move_on_end: self.move_on_end,
507 start_bound: self.start_bound,
508 end_bound: self.end_bound,
509 _phantom: marker::PhantomData,
510 }
511 }
512
513 /// Move through key/values entries and output duplicate values.
514 ///
515 /// For more info, see [`RoIter::move_through_duplicate_values`].
516 pub fn move_through_duplicate_values(
517 self,
518 ) -> RoRevRange<'txn, KC, DC, C, MoveThroughDuplicateValues> {
519 RoRevRange {
520 cursor: self.cursor,
521 move_on_end: self.move_on_end,
522 start_bound: self.start_bound,
523 end_bound: self.end_bound,
524 _phantom: marker::PhantomData,
525 }
526 }
527
528 /// Change the codec types of this iterator, specifying the codecs.
529 pub fn remap_types<KC2, DC2>(self) -> RoRevRange<'txn, KC2, DC2, C, IM> {
530 RoRevRange {
531 cursor: self.cursor,
532 move_on_end: self.move_on_end,
533 start_bound: self.start_bound,
534 end_bound: self.end_bound,
535 _phantom: marker::PhantomData,
536 }
537 }
538
539 /// Change the key codec type of this iterator, specifying the new codec.
540 pub fn remap_key_type<KC2>(self) -> RoRevRange<'txn, KC2, DC, C, IM> {
541 self.remap_types::<KC2, DC>()
542 }
543
544 /// Change the data codec type of this iterator, specifying the new codec.
545 pub fn remap_data_type<DC2>(self) -> RoRevRange<'txn, KC, DC2, C, IM> {
546 self.remap_types::<KC, DC2>()
547 }
548
549 /// Wrap the data bytes into a lazy decoder.
550 pub fn lazily_decode_data(self) -> RoRevRange<'txn, KC, LazyDecode<DC>, C, IM> {
551 self.remap_types::<KC, LazyDecode<DC>>()
552 }
553 }
554
555 impl<'txn, KC, DC, C, IM> Iterator for RoRevRange<'txn, KC, DC, C, IM>
556 where
557 KC: BytesDecode<'txn>,
558 DC: BytesDecode<'txn>,
559 IM: IterationMethod,
560 C: Comparator,
561 {
562 type Item = Result<(KC::DItem, DC::DItem)>;
563
564 fn next(&mut self) -> Option<Self::Item> {
565 let result = if self.move_on_end {
566 self.move_on_end = false;
567 move_on_range_end(&mut self.cursor, &self.end_bound)
568 } else {
569 self.cursor.move_on_prev(IM::MOVE_OPERATION)
570 };
571
572 match result {
573 Ok(Some((key, data))) => {
574 let must_be_returned = match &self.start_bound {
575 Bound::Included(start) => C::compare(key, start).is_ge(),
576 Bound::Excluded(start) => C::compare(key, start).is_gt(),
577 Bound::Unbounded => true,
578 };
579
580 if must_be_returned {
581 match (KC::bytes_decode(key), DC::bytes_decode(data)) {
582 (Ok(key), Ok(data)) => Some(Ok((key, data))),
583 (Err(e), _) | (_, Err(e)) => Some(Err(Error::Decoding(e))),
584 }
585 } else {
586 None
587 }
588 }
589 Ok(None) => None,
590 Err(e) => Some(Err(e)),
591 }
592 }
593
594 fn last(mut self) -> Option<Self::Item> {
595 let result = if self.move_on_end {
596 move_on_range_start(&mut self.cursor, &mut self.start_bound)
597 } else {
598 let current = self.cursor.current();
599 let start = move_on_range_start(&mut self.cursor, &mut self.start_bound);
600 match (current, start) {
601 (Ok(Some((ckey, _))), Ok(Some((key, data)))) if C::compare(ckey, key).is_ne() => {
602 Ok(Some((key, data)))
603 }
604 (Ok(_), Ok(_)) => Ok(None),
605 (Err(e), _) | (_, Err(e)) => Err(e),
606 }
607 };
608
609 match result {
610 Ok(Some((key, data))) => {
611 let must_be_returned = match &self.end_bound {
612 Bound::Included(end) => C::compare(key, end).is_le(),
613 Bound::Excluded(end) => C::compare(key, end).is_lt(),
614 Bound::Unbounded => true,
615 };
616
617 if must_be_returned {
618 match (KC::bytes_decode(key), DC::bytes_decode(data)) {
619 (Ok(key), Ok(data)) => Some(Ok((key, data))),
620 (Err(e), _) | (_, Err(e)) => Some(Err(Error::Decoding(e))),
621 }
622 } else {
623 None
624 }
625 }
626 Ok(None) => None,
627 Err(e) => Some(Err(e)),
628 }
629 }
630 }
631
632 impl<KC, DC, C, IM> fmt::Debug for RoRevRange<'_, KC, DC, C, IM> {
633 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
634 f.debug_struct("RoRevRange").finish()
635 }
636 }
637
638 /// A reverse read-write range iterator structure.
639 pub struct RwRevRange<'txn, KC, DC, C = DefaultComparator, IM = MoveThroughDuplicateValues> {
640 cursor: RwCursor<'txn>,
641 move_on_end: bool,
642 start_bound: Bound<Vec<u8>>,
643 end_bound: Bound<Vec<u8>>,
644 _phantom: marker::PhantomData<(KC, DC, C, IM)>,
645 }
646
647 impl<'txn, KC, DC, C, IM> RwRevRange<'txn, KC, DC, C, IM> {
648 pub(crate) fn new(
649 cursor: RwCursor<'txn>,
650 start_bound: Bound<Vec<u8>>,
651 end_bound: Bound<Vec<u8>>,
652 ) -> RwRevRange<'txn, KC, DC, C, IM> {
653 RwRevRange {
654 cursor,
655 move_on_end: true,
656 start_bound,
657 end_bound,
658 _phantom: marker::PhantomData,
659 }
660 }
661
662 /// Delete the entry the cursor is currently pointing to.
663 ///
664 /// Returns `true` if the entry was successfully deleted.
665 ///
666 /// # Safety
667 ///
668 /// It is _[undefined behavior]_ to keep a reference of a value from this database
669 /// while modifying it.
670 ///
671 /// > [Values returned from the database are valid only until a subsequent update operation,
672 /// > or the end of the transaction.](http://www.lmdb.tech/doc/group__mdb.html#structMDB__val)
673 ///
674 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
675 pub unsafe fn del_current(&mut self) -> Result<bool> {
676 self.cursor.del_current()
677 }
678
679 /// Write a new value to the current entry.
680 ///
681 /// The given key **must** be equal to the one this cursor is pointing otherwise the database
682 /// can be put into an inconsistent state.
683 ///
684 /// Returns `true` if the entry was successfully written.
685 ///
686 /// > This is intended to be used when the new data is the same size as the old.
687 /// > Otherwise it will simply perform a delete of the old record followed by an insert.
688 ///
689 /// # Safety
690 ///
691 /// It is _[undefined behavior]_ to keep a reference of a value from this database while
692 /// modifying it, so you can't use the key/value that comes from the cursor to feed
693 /// this function.
694 ///
695 /// In other words: Transform the key and value that you borrow from this database into an owned
696 /// version of them (e.g. `&str` into `String`).
697 ///
698 /// > [Values returned from the database are valid only until a subsequent update operation,
699 /// > or the end of the transaction.](http://www.lmdb.tech/doc/group__mdb.html#structMDB__val)
700 ///
701 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
702 pub unsafe fn put_current<'a>(
703 &mut self,
704 key: &'a KC::EItem,
705 data: &'a DC::EItem,
706 ) -> Result<bool>
707 where
708 KC: BytesEncode<'a>,
709 DC: BytesEncode<'a>,
710 {
711 let key_bytes: Cow<[u8]> = KC::bytes_encode(key).map_err(Error::Encoding)?;
712 let data_bytes: Cow<[u8]> = DC::bytes_encode(data).map_err(Error::Encoding)?;
713 self.cursor.put_current(&key_bytes, &data_bytes)
714 }
715
716 /// Write a new value to the current entry. The entry is written with the specified flags.
717 ///
718 /// The given key **must** be equal to the one this cursor is pointing otherwise the database
719 /// can be put into an inconsistent state.
720 ///
721 /// Returns `true` if the entry was successfully written.
722 ///
723 /// > This is intended to be used when the new data is the same size as the old.
724 /// > Otherwise it will simply perform a delete of the old record followed by an insert.
725 ///
726 /// # Safety
727 ///
728 /// Please read the safety notes of the [`RwRevRange::put_current`] method.
729 pub unsafe fn put_current_reserved_with_flags<'a, F>(
730 &mut self,
731 flags: PutFlags,
732 key: &'a KC::EItem,
733 data_size: usize,
734 write_func: F,
735 ) -> Result<bool>
736 where
737 KC: BytesEncode<'a>,
738 F: FnOnce(&mut ReservedSpace) -> io::Result<()>,
739 {
740 let key_bytes: Cow<[u8]> = KC::bytes_encode(key).map_err(Error::Encoding)?;
741 self.cursor.put_current_reserved_with_flags(flags, &key_bytes, data_size, write_func)
742 }
743
744 /// Insert a key-value pair in this database. The entry is written with the specified flags and data codec.
745 ///
746 /// For more info, see [`RwIter::put_current_with_options`].
747 ///
748 /// # Safety
749 ///
750 /// It is _[undefined behavior]_ to keep a reference of a value from this database while
751 /// modifying it, so you can't use the key/value that comes from the cursor to feed
752 /// this function.
753 ///
754 /// In other words: Transform the key and value that you borrow from this database into an owned
755 /// version of them (e.g. `&str` into `String`).
756 ///
757 /// > [Values returned from the database are valid only until a subsequent update operation,
758 /// > or the end of the transaction.](http://www.lmdb.tech/doc/group__mdb.html#structMDB__val)
759 ///
760 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
761 pub unsafe fn put_current_with_options<'a, NDC>(
762 &mut self,
763 flags: PutFlags,
764 key: &'a KC::EItem,
765 data: &'a NDC::EItem,
766 ) -> Result<()>
767 where
768 KC: BytesEncode<'a>,
769 NDC: BytesEncode<'a>,
770 {
771 let key_bytes: Cow<[u8]> = KC::bytes_encode(key).map_err(Error::Encoding)?;
772 let data_bytes: Cow<[u8]> = NDC::bytes_encode(data).map_err(Error::Encoding)?;
773 self.cursor.put_current_with_flags(flags, &key_bytes, &data_bytes)
774 }
775
776 /// Move on the first value of keys, ignoring duplicate values.
777 ///
778 /// For more info, see [`RoIter::move_between_keys`].
779 pub fn move_between_keys(self) -> RwRevRange<'txn, KC, DC, C, MoveBetweenKeys> {
780 RwRevRange {
781 cursor: self.cursor,
782 move_on_end: self.move_on_end,
783 start_bound: self.start_bound,
784 end_bound: self.end_bound,
785 _phantom: marker::PhantomData,
786 }
787 }
788
789 /// Move through key/values entries and output duplicate values.
790 ///
791 /// For more info, see [`RoIter::move_through_duplicate_values`].
792 pub fn move_through_duplicate_values(
793 self,
794 ) -> RwRevRange<'txn, KC, DC, C, MoveThroughDuplicateValues> {
795 RwRevRange {
796 cursor: self.cursor,
797 move_on_end: self.move_on_end,
798 start_bound: self.start_bound,
799 end_bound: self.end_bound,
800 _phantom: marker::PhantomData,
801 }
802 }
803
804 /// Change the codec types of this iterator, specifying the codecs.
805 pub fn remap_types<KC2, DC2>(self) -> RwRevRange<'txn, KC2, DC2, C, IM> {
806 RwRevRange {
807 cursor: self.cursor,
808 move_on_end: self.move_on_end,
809 start_bound: self.start_bound,
810 end_bound: self.end_bound,
811 _phantom: marker::PhantomData,
812 }
813 }
814
815 /// Change the key codec type of this iterator, specifying the new codec.
816 pub fn remap_key_type<KC2>(self) -> RwRevRange<'txn, KC2, DC, C, IM> {
817 self.remap_types::<KC2, DC>()
818 }
819
820 /// Change the data codec type of this iterator, specifying the new codec.
821 pub fn remap_data_type<DC2>(self) -> RwRevRange<'txn, KC, DC2, C, IM> {
822 self.remap_types::<KC, DC2>()
823 }
824
825 /// Wrap the data bytes into a lazy decoder.
826 pub fn lazily_decode_data(self) -> RwRevRange<'txn, KC, LazyDecode<DC>, C, IM> {
827 self.remap_types::<KC, LazyDecode<DC>>()
828 }
829 }
830
831 impl<'txn, KC, DC, C, IM> Iterator for RwRevRange<'txn, KC, DC, C, IM>
832 where
833 KC: BytesDecode<'txn>,
834 DC: BytesDecode<'txn>,
835 IM: IterationMethod,
836 C: Comparator,
837 {
838 type Item = Result<(KC::DItem, DC::DItem)>;
839
840 fn next(&mut self) -> Option<Self::Item> {
841 let result = if self.move_on_end {
842 self.move_on_end = false;
843 move_on_range_end(&mut self.cursor, &self.end_bound)
844 } else {
845 self.cursor.move_on_prev(IM::MOVE_OPERATION)
846 };
847
848 match result {
849 Ok(Some((key, data))) => {
850 let must_be_returned = match &self.start_bound {
851 Bound::Included(start) => C::compare(key, start).is_ge(),
852 Bound::Excluded(start) => C::compare(key, start).is_gt(),
853 Bound::Unbounded => true,
854 };
855
856 if must_be_returned {
857 match (KC::bytes_decode(key), DC::bytes_decode(data)) {
858 (Ok(key), Ok(data)) => Some(Ok((key, data))),
859 (Err(e), _) | (_, Err(e)) => Some(Err(Error::Decoding(e))),
860 }
861 } else {
862 None
863 }
864 }
865 Ok(None) => None,
866 Err(e) => Some(Err(e)),
867 }
868 }
869
870 fn last(mut self) -> Option<Self::Item> {
871 let result = if self.move_on_end {
872 move_on_range_start(&mut self.cursor, &mut self.start_bound)
873 } else {
874 let current = self.cursor.current();
875 let start = move_on_range_start(&mut self.cursor, &mut self.start_bound);
876 match (current, start) {
877 (Ok(Some((ckey, _))), Ok(Some((key, data)))) if C::compare(ckey, key).is_ne() => {
878 Ok(Some((key, data)))
879 }
880 (Ok(_), Ok(_)) => Ok(None),
881 (Err(e), _) | (_, Err(e)) => Err(e),
882 }
883 };
884
885 match result {
886 Ok(Some((key, data))) => {
887 let must_be_returned = match &self.end_bound {
888 Bound::Included(end) => C::compare(key, end).is_le(),
889 Bound::Excluded(end) => C::compare(key, end).is_lt(),
890 Bound::Unbounded => true,
891 };
892
893 if must_be_returned {
894 match (KC::bytes_decode(key), DC::bytes_decode(data)) {
895 (Ok(key), Ok(data)) => Some(Ok((key, data))),
896 (Err(e), _) | (_, Err(e)) => Some(Err(Error::Decoding(e))),
897 }
898 } else {
899 None
900 }
901 }
902 Ok(None) => None,
903 Err(e) => Some(Err(e)),
904 }
905 }
906 }
907
908 impl<KC, DC, C, IM> fmt::Debug for RwRevRange<'_, KC, DC, C, IM> {
909 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
910 f.debug_struct("RwRevRange").finish()
911 }
912 }