Debian Codegraph @

src/iterator/iter.rs

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