ord-lmdb-zero 0.4.5

An almost-safe, near-zero-cost, feature-complete, unabashedly non-abstract wrapper around LMDB.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
// Copyright 2016 FullContact, Inc
// Copyright 2017, 2018 Jason Lingle
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::mem;
use std::ptr;
use libc::{self, c_void};

use ffi;
use supercow::{NonSyncSupercow, Supercow, Phantomcow};

use env::Environment;
use error::Result;
use mdb_vals::*;
use traits::*;
use dbi::Database;
use tx::{self, put, del, ConstAccessor, ConstTransaction, WriteAccessor};
use tx::assert_sensible_cursor;

#[derive(Debug)]
struct CursorHandle(*mut ffi::MDB_cursor);
impl Drop for CursorHandle {
    fn drop(&mut self) {
        unsafe {
            ffi::mdb_cursor_close(self.0);
        }
    }
}

/// A cursor into an LMDB database.
///
/// Depending on the context, a cursor's lifetime may be scoped to a
/// transaction or to the whole environment. Its lifetime is also naturally
/// bound to the lifetime of the database it cursors into.
///
/// ## Creation and Ownership
///
/// Cursors are normally created by calling `.cursor()` on the transaction that
/// is to own them. Since a `Cursor` is associated with a `Database`, this also
/// involves passing a reference or other handle to that `Database` to the
/// call.
///
/// For the `Database`, all three ownership models are permitted, though owned
/// likely is not useful. The transaction can be used with borrowed or shared
/// ownership, but note that shared ownership requires having the
/// `CreateCursor` trait imported.
///
/// ### Example — Traditional "keep everything on the stack" style
///
/// This is the simplest way to use `Cursor`, but not always the easiest. Most
/// examples in the documentation use this method. Here, the `Cursor` holds
/// references to the transaction and the database. This makes it somewhat
/// inflexible; for example, you cannot make a structure which owns both the
/// transaction and some set of cursors.
///
/// ```
/// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
/// # fn main() {
/// # let env = create_env();
/// # let db = defdb(&env);
/// # let txn = lmdb::WriteTransaction::new(&env).unwrap();
/// # run(&txn, &mut txn.access(), &db);
/// # }
/// // N.B. Unneeded type and lifetime annotations here for clarity.
/// fn run<'db, 'txn>(txn: &'txn lmdb::WriteTransaction,
///                   access: &'txn mut lmdb::WriteAccessor,
///                   db: &'db lmdb::Database) {
///   let mut cursor: lmdb::Cursor<'txn, 'db> = txn.cursor(db).unwrap();
///   // Do stuff with cursor.
/// # ::std::mem::drop(cursor);
/// }
/// ```
///
/// ### Example — Use reference counting for more flexibility
///
/// ```
/// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
/// use std::sync::Arc;
///
/// // We need to import the `CreateCursor` trait to be able to use shared
/// // mode cursors. `TxExt` also gets us `to_const()` used below.
/// use lmdb::traits::{CreateCursor, TxExt};
///
/// // This approach lets us make this `Context` struct wherein we can pass
/// // around everything our functions might need in one piece as well as
/// // having more flexible transaction lifetimes.
/// struct Context {
///   txn: Arc<lmdb::ConstTransaction<'static>>,
///   cursor: Arc<lmdb::Cursor<'static,'static>>,
/// }
///
/// // N.B. Unneeded type and lifetime annotations here for clarity.
///
/// # fn main() {
/// // Everything at higher levels also needs to have `'static` lifetimes.
/// // Here, we just stuff everything into `Arc`s for simplicity.
/// let env: Arc<lmdb::Environment> = Arc::new(create_env());
/// let db: Arc<lmdb::Database<'static>> = Arc::new(lmdb::Database::open(
///   env.clone(), None, &lmdb::DatabaseOptions::defaults()).unwrap());
///
/// // Now we can make our transaction and cursor and pass them around as one.
/// // Note that you can also use plain `Rc` at this level, too.
/// let txn: Arc<lmdb::WriteTransaction<'static>> =
///   Arc::new(lmdb::WriteTransaction::new(env.clone()).unwrap());
/// let cursor: Arc<lmdb::Cursor<'static, 'static>> = Arc::new(
///   txn.cursor(db.clone()).unwrap());
/// let context = Context { txn: txn.clone().to_const(), cursor: cursor };
/// do_stuff(&context);
///
/// // Drop the context so we can get the `WriteTransaction` back
/// // and commit it.
/// drop(context);
/// let txn = Arc::try_unwrap(txn).unwrap();
/// txn.commit().unwrap();
/// # }
///
/// #[allow(unused_vars)]
/// fn do_stuff(context: &Context) {
///   // do stuff
/// }
/// ```
///
/// ## Lifetime
///
/// A cursor must be strictly outlived by both the transaction that created it
/// and by the database into which it indexes. The two lifetimes are needed to
/// permit a cursor to be disassociated from its transaction and rebound to a
/// later transaction.
///
/// `Cursor` is covariant on both of its lifetimes. If you have an owned
/// `Cursor` as a structure member and don't plan on using the `dissoc_cursor`
/// API, you can use one lifetime parameter to fill both without issue.
///
/// ```rust,norun
/// # #![allow(dead_code)]
/// # extern crate lmdb_zero as lmdb;
/// # fn main() { }
/// #
/// struct CursorOwner<'a> {
///   cursor: lmdb::Cursor<'a, 'a>,
/// }
/// fn covariance<'a, 'txn: 'a, 'db: 'a>(c: lmdb::Cursor<'txn,'db>)
///                                     -> CursorOwner<'a> {
///   let c: lmdb::Cursor<'a, 'a> = c;
///   CursorOwner { cursor: c }
/// }
/// ```
///
/// Note that an `&mut Cursor<'txn,'db>` is naturally _invariant_ on both
/// lifetimes. This means that structures containing `&mut Cursor` or functions
/// taking them as references should generally include both.
///
/// ```rust,norun
/// # #![allow(dead_code)]
/// # extern crate lmdb_zero as lmdb;
/// # fn main() { }
/// #
/// // Write this
/// fn do_stuff_with_cursor<'txn, 'db>(c: &mut lmdb::Cursor<'txn,'db>) {
///   // Stuff
/// }
/// // Not this
/// fn do_stuff_with_cursor_2<'a>(c: &mut lmdb::Cursor<'a,'a>) {
///   // Stuff
/// }
/// ```
///
/// Attempting to unify the lifetimes on a `&mut Cursor` will often work, but
/// can also cause the compiler to infer lifetimes in unfavourable ways.
#[derive(Debug)]
pub struct Cursor<'txn,'db> {
    cursor: CursorHandle,
    txn: NonSyncSupercow<'txn, ConstTransaction<'txn>>,
    _db: Phantomcow<'db, Database<'db>>,
}

// Used by transactions to construct/query cursors
pub unsafe fn create_cursor<'txn, 'db>(
    raw: *mut ffi::MDB_cursor,
    txn: NonSyncSupercow<'txn, ConstTransaction<'txn>>,
    db: Phantomcow<'db, Database<'db>>)
    -> Cursor<'txn, 'db>
{
    Cursor {
        cursor: CursorHandle(raw),
        txn: txn,
        _db: db,
    }
}
pub fn txn_ref<'a,'txn: 'a,'db>(cursor: &'a Cursor<'txn,'db>)
                                -> &'a ConstTransaction<'txn> {
    &*cursor.txn
}

/// A read-only cursor which has been dissociated from its original
/// transaction, so that it can be rebound later.
///
/// A `StaleCursor` remains bound to the original database.
#[derive(Debug)]
pub struct StaleCursor<'db> {
    cursor: CursorHandle,
    env: NonSyncSupercow<'db, Environment>,
    _db: Phantomcow<'db, Database<'db>>,
}

// Internal
pub fn to_stale<'a,'db>(cursor: Cursor<'a,'db>,
                        env: NonSyncSupercow<'db, Environment>)
                        -> StaleCursor<'db> {
    StaleCursor {
        cursor: cursor.cursor,
        env: env,
        _db: cursor._db,
    }
}
pub fn env_ref<'a,'db>(cursor: &'a StaleCursor<'db>)
                       -> &'a Environment {
    &*cursor.env
}
pub fn stale_cursor_ptr<'db>(cursor: &StaleCursor<'db>)
                             -> *mut ffi::MDB_cursor {
    cursor.cursor.0
}

macro_rules! cursor_get_0_kv {
    ($(#[$doc:meta])* fn $method:ident, $op:path) => {
        $(#[$doc])*
        #[inline]
        pub fn $method<'access, K : FromLmdbBytes + ?Sized,
                       V : FromLmdbBytes + ?Sized>
            (&mut self, access: &'access ConstAccessor)
             -> Result<(&'access K, &'access V)>
        {
            self.get_0_kv(access, $op)
        }
    }
}

macro_rules! cursor_get_0_v {
    ($(#[$doc:meta])* fn $method:ident, $op:path) => {
        $(#[$doc])*
        #[inline]
        pub fn $method<'access, V : FromLmdbBytes + ?Sized>
            (&mut self, access: &'access ConstAccessor)
             -> Result<(&'access V)>
        {
            self.get_0_v(access, $op)
        }
    }
}

impl<'txn,'db> Cursor<'txn,'db> {
    /// Directly construct a cursor with the given transaction and database
    /// handles.
    ///
    /// This is a low-level function intended only for use by implementations
    /// of the `CreateCursor` trait. (There is nothing less safe about it being
    /// low-level; it's simply inconvenient.)
    pub fn construct(
        txn: NonSyncSupercow<'txn, ConstTransaction<'txn>>,
        db: Supercow<'db, Database<'db>>)
        -> Result<Self>
    {
        try!(tx::assert_same_env(&txn, &db));

        let mut raw: *mut ffi::MDB_cursor = ptr::null_mut();
        unsafe {
            lmdb_call!(ffi::mdb_cursor_open(tx::txptr(&txn), db.as_raw(),
                                            &mut raw));
        }

        Ok(unsafe { create_cursor(raw, txn,
                                  Supercow::phantom(db)) })
    }

    /// Directly renew a `StaleCursor` into a functional `Cursor` using the
    /// given database handle.
    ///
    /// This is a low-level function intended only for use by implementations
    /// of the `AssocCursor` trait. (There is nothing less safe about it being
    /// low-level; it's simply inconvenient.)
    ///
    /// It is an error if `txn` is not actually a `ReadTransaction`.
    pub fn from_stale(
        stale: StaleCursor<'db>,
        txn: NonSyncSupercow<'txn, ConstTransaction<'txn>>)
        -> Result<Self>
    {
        try!(tx::assert_in_env(&txn, env_ref(&stale)));

        unsafe {
            lmdb_call!(ffi::mdb_cursor_renew(
                tx::txptr(&txn), stale_cursor_ptr(&stale)));
        }

        Ok(Cursor {
            cursor: stale.cursor,
            txn: txn,
            _db: stale._db,
        })
    }

    #[inline]
    fn get_0_kv<'access, K : FromLmdbBytes + ?Sized,
                V : FromLmdbBytes + ?Sized>
        (&mut self, access: &'access ConstAccessor,
         op: ffi::MDB_cursor_op) -> Result<(&'access K, &'access V)>
    {
        try!(assert_sensible_cursor(access, self));

        let mut out_key = EMPTY_VAL;
        let mut out_val = EMPTY_VAL;
        unsafe {
            lmdb_call!(ffi::mdb_cursor_get(
                self.cursor.0, &mut out_key, &mut out_val, op));
        }

        Ok((try!(from_val(access, &out_key)),
            try!(from_val(access, &out_val))))
    }

    #[inline]
    fn get_0_v<'access, V : FromLmdbBytes + ?Sized>
        (&mut self, access: &'access ConstAccessor,
         op: ffi::MDB_cursor_op) -> Result<&'access V>
    {
        try!(assert_sensible_cursor(access, self));

        let mut null_key = EMPTY_VAL;
        let mut out_val = EMPTY_VAL;
        unsafe {
            lmdb_call!(ffi::mdb_cursor_get(
                self.cursor.0, &mut null_key, &mut out_val, op));
        }

        from_val(access, &out_val)
    }

    #[inline]
    fn get_kv_0<K: AsLmdbBytes + ?Sized, V : AsLmdbBytes + ?Sized>
        (&mut self, key: &K, val: &V, op: ffi::MDB_cursor_op) -> Result<()>
    {
        let mut mv_key = as_val(key);
        let mut mv_val = as_val(val);
        unsafe {
            lmdb_call!(ffi::mdb_cursor_get(
                self.cursor.0, &mut mv_key, &mut mv_val, op));
        }

        Ok(())
    }

    #[inline]
    fn get_kv_v<'access, K : AsLmdbBytes + ?Sized,
                V : AsLmdbBytes + FromLmdbBytes + ?Sized>
        (&mut self, access: &'access ConstAccessor,
         key: &K, val: &V, op: ffi::MDB_cursor_op) -> Result<&'access V>
    {
        try!(assert_sensible_cursor(access, self));

        let mut mv_key = as_val(key);
        let mut inout_val = as_val(val);

        unsafe {
            lmdb_call!(ffi::mdb_cursor_get(
                self.cursor.0, &mut mv_key, &mut inout_val, op));
        }

        from_val(access, &inout_val)
    }

    #[inline]
    fn get_k_v<'access, K : AsLmdbBytes + ?Sized,
               V : FromLmdbBytes + ?Sized>
        (&mut self, access: &'access ConstAccessor,
         key: &K, op: ffi::MDB_cursor_op) -> Result<&'access V>
    {
        try!(assert_sensible_cursor(access, self));

        let mut mv_key = as_val(key);
        let mut out_val = EMPTY_VAL;

        unsafe {
            lmdb_call!(ffi::mdb_cursor_get(
                self.cursor.0, &mut mv_key, &mut out_val, op));
        }

        from_val(access, &out_val)
    }

    #[inline]
    fn get_k_kv<'access, K : AsLmdbBytes + FromLmdbBytes + ?Sized,
                V : FromLmdbBytes + ?Sized>
        (&mut self, access: &'access ConstAccessor,
         key: &K, op: ffi::MDB_cursor_op) -> Result<(&'access K, &'access V)>
    {
        try!(assert_sensible_cursor(access, self));

        let mut inout_key = as_val(key);
        let mut out_val = EMPTY_VAL;

        unsafe {
            lmdb_call!(ffi::mdb_cursor_get(
                self.cursor.0, &mut inout_key, &mut out_val, op));
        }

        Ok((try!(from_val(access, &inout_key)),
            try!(from_val(access, &out_val))))
    }

    cursor_get_0_kv! {
        /// Positions the cursor at the first key/value pair in the database
        /// and returns that pair.
        ///
        /// This corresponds to the `mdb_cursor_get` function with the
        /// `MDB_FIRST` operation.
        ///
        /// ## Example
        ///
        /// ```
        /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
        /// # fn main() {
        /// # let env = create_env();
        /// # let db = dupdb(&env);
        /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
        /// {
        ///   let mut access = txn.access();
        ///   let f = lmdb::put::Flags::empty();
        ///   access.put(&db, "Germany", "Berlin", f).unwrap();
        ///   access.put(&db, "France", "Paris", f).unwrap();
        ///   access.put(&db, "Latvia", "Rīga", f).unwrap();
        ///
        ///   let mut cursor = txn.cursor(&db).unwrap();
        ///   assert_eq!(("France", "Paris"), cursor.first(&access).unwrap());
        /// }
        /// txn.commit().unwrap();
        /// # }
        /// ```
        fn first, ffi::MDB_cursor_op::MDB_FIRST
    }

    cursor_get_0_v! {
        /// Positions the cursor at the first key/value pair whose key is equal
        /// to the current key, returning the value of that pair.
        ///
        /// This only makes sense on `DUPSORT` databases.
        ///
        /// This correspnods to the `mdb_cursor_get` function with the
        /// `MDB_FIRST_DUP` operation.
        ///
        /// ## Example
        ///
        /// ```
        /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
        /// # fn main() {
        /// # let env = create_env();
        /// # let db = dupdb(&env);
        /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
        /// {
        ///   let mut access = txn.access();
        ///   let f = lmdb::put::Flags::empty();
        ///   access.put(&db, "Fruit", "Apple", f).unwrap();
        ///   access.put(&db, "Fruit", "Orange", f).unwrap();
        ///   access.put(&db, "Fruit", "Durian", f).unwrap();
        ///   access.put(&db, "Animal", "Badger", f).unwrap();
        ///
        ///   let mut cursor = txn.cursor(&db).unwrap();
        ///   assert_eq!(("Fruit", "Orange"), cursor.last(&access).unwrap());
        ///   assert_eq!("Apple", cursor.first_dup::<str>(&access).unwrap());
        /// }
        /// txn.commit().unwrap();
        /// # }
        /// ```
        fn first_dup, ffi::MDB_cursor_op::MDB_FIRST_DUP
    }

    /// Positions the cursor at the given (key,value) pair.
    ///
    /// This only makes sense on `DUPSORT` databases.
    ///
    /// This corresponds to the `mdb_cursor_get` function with the
    /// `MDB_GET_BOTH` operation.
    ///
    /// ## Example
    ///
    /// ```
    /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
    /// # fn main() {
    /// # let env = create_env();
    /// # let db = dupdb(&env);
    /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
    /// {
    ///   let mut access = txn.access();
    ///   let f = lmdb::put::Flags::empty();
    ///   access.put(&db, "Fruit", "Apple", f).unwrap();
    ///   access.put(&db, "Fruit", "Orange", f).unwrap();
    ///   access.put(&db, "Fruit", "Durian", f).unwrap();
    ///   access.put(&db, "Animal", "Badger", f).unwrap();
    ///
    ///   let mut cursor = txn.cursor(&db).unwrap();
    ///   cursor.seek_kv("Fruit", "Durian").unwrap();
    ///   assert_eq!(("Fruit", "Orange"), cursor.next(&access).unwrap());
    ///   assert!(cursor.seek_kv("Fruit", "Lychee").is_err());
    /// }
    /// txn.commit().unwrap();
    /// # }
    /// ```
    #[inline]
    pub fn seek_kv<K : AsLmdbBytes + ?Sized, V : AsLmdbBytes + ?Sized>
        (&mut self, key: &K, val: &V) -> Result<()>
    {
        self.get_kv_0(key, val, ffi::MDB_cursor_op::MDB_GET_BOTH)
    }

    /// Positions the cursor at the given key and the "nearest" value to `val`,
    /// that is, the first (according to sorting) item whose key equals `key`
    /// and whose value is greater than or equal to `val`.
    ///
    /// The actual value found is returned.
    ///
    /// This only makes sense on `DUPSORT` databases.
    ///
    /// This corresponds to the `mdb_cursor_get` function with the
    /// `MDB_GET_BOTH_RANGE` operation.
    ///
    /// ## Example
    ///
    /// ```
    /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
    /// # fn main() {
    /// # let env = create_env();
    /// # let db = dupdb(&env);
    /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
    /// {
    ///   let mut access = txn.access();
    ///   let f = lmdb::put::Flags::empty();
    ///   access.put(&db, "Animal", "Badger", f).unwrap();
    ///   access.put(&db, "Fruit", "Banana", f).unwrap();
    ///   access.put(&db, "Fruit", "Orange", f).unwrap();
    ///   access.put(&db, "Fruit", "Durian", f).unwrap();
    ///   access.put(&db, "Veggie", "Carrot", f).unwrap();
    ///
    ///   let mut cursor = txn.cursor(&db).unwrap();
    ///   assert_eq!("Durian", cursor.seek_k_nearest_v::<str,str>(
    ///     &access, "Fruit", "Durian").unwrap());
    ///   assert_eq!("Orange", cursor.seek_k_nearest_v::<str,str>(
    ///     &access, "Fruit", "Lychee").unwrap());
    ///   assert!(cursor.seek_k_nearest_v::<str,str>(
    ///     &access, "Fruit", "Watermelon").is_err());
    ///   assert_eq!("Banana", cursor.seek_k_nearest_v::<str,str>(
    ///     &access, "Fruit", "Apple").unwrap());
    ///   assert!(cursor.seek_k_nearest_v::<str,str>(
    ///     &access, "Plant", "Tree").is_err());
    /// }
    /// txn.commit().unwrap();
    /// # }
    /// ```
    #[inline]
    pub fn seek_k_nearest_v<'access, K : AsLmdbBytes + ?Sized,
                            V : AsLmdbBytes + FromLmdbBytes + ?Sized>
        (&mut self, access: &'access ConstAccessor,
         key: &K, val: &V) -> Result<&'access V>
    {
        self.get_kv_v(access, key, val, ffi::MDB_cursor_op::MDB_GET_BOTH_RANGE)
    }

    cursor_get_0_kv! {
        /// Returns the current key/value pair under this cursor.
        ///
        /// This corresponds to the `mdb_cursor_get` function with the
        /// `MDB_CURRENT` operation.
        ///
        /// ## Example
        ///
        /// ```
        /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
        /// # fn main() {
        /// # let env = create_env();
        /// # let db = dupdb(&env);
        /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
        /// {
        ///   let mut access = txn.access();
        ///   let f = lmdb::put::Flags::empty();
        ///   access.put(&db, "Germany", "Berlin", f).unwrap();
        ///   access.put(&db, "France", "Paris", f).unwrap();
        ///   access.put(&db, "Latvia", "Rīga", f).unwrap();
        ///
        ///   let mut cursor = txn.cursor(&db).unwrap();
        ///   cursor.seek_k::<str,str>(&access, "Latvia").unwrap();
        ///   assert_eq!(("Latvia", "Rīga"), cursor.get_current(&access).unwrap());
        /// }
        /// txn.commit().unwrap();
        /// # }
        /// ```
        fn get_current, ffi::MDB_cursor_op::MDB_GET_CURRENT
    }

    /// Returns as many items as possible with the current key from the
    /// current cursor position.
    ///
    /// The cursor is advanced so that `next_multiple()` returns the next
    /// group of items, if any. Note that this does _not_ return the actual
    /// key (which LMDB itself does not return, contrary to documentation).
    ///
    /// The easiest way to use this is for `V` to be a slice of `LmdbRaw`
    /// types.
    ///
    /// This only makes sense on `DUPSORT` databases with `DUPFIXED` set.
    ///
    /// This corresponds to the `mdb_cursor_get` function with the
    /// `MDB_GET_MULTIPLE` operation, except that it does not have a special
    /// case if exactly one value is bound to the key.
    ///
    /// See `lmdb_zero::db::DUPFIXED` for examples of usage.
    #[inline]
    pub fn get_multiple<'access, V : FromLmdbBytes + ?Sized>
        (&mut self, access: &'access ConstAccessor)
         -> Result<(&'access V)>
    {
        try!(assert_sensible_cursor(access, self));

        let mut null_key = EMPTY_VAL;
        let mut out_val = EMPTY_VAL;
        unsafe {
            lmdb_call!(ffi::mdb_cursor_get(
                self.cursor.0, &mut null_key, &mut out_val,
                ffi::MDB_cursor_op::MDB_GET_MULTIPLE));
        }

        if out_val.mv_data.is_null() {
            // LMDB seemingly intentionally returns SUCCESS but a NULL data
            // pointer if there's exactly one element.
            // https://github.com/LMDB/lmdb/blob/0a2622317f189c7062d03d050be6766586a548b2/libraries/liblmdb/mdb.c#L7228
            // Presumably it has something to do with the fact that single
            // values are stored differently than dup values, though it's
            // unclear why it doesn't do what we do here. If we see this
            // condition, simply fall back to MDB_GET_CURRENT which doesn't
            // modify the cursor, so the caller's follow-up call to
            // next_multiple() will still be sound.
            unsafe {
                lmdb_call!(ffi::mdb_cursor_get(
                    self.cursor.0, &mut null_key, &mut out_val,
                    ffi::MDB_cursor_op::MDB_GET_CURRENT));
            }
        }

        from_val(access, &out_val)

    }

    cursor_get_0_v! {
        /// Continues fetching items from a cursor positioned by a call to
        /// `get_multiple()`.
        ///
        /// This corresponds to the `mdb_cursor_get` function with the
        /// `MDB_NEXT_MULTIPLE` operation.
        ///
        /// See `lmdb_zero::db::DUPFIXED` for examples of usage.
        fn next_multiple, ffi::MDB_cursor_op::MDB_NEXT_MULTIPLE
    }

    cursor_get_0_kv! {
        /// Positions the cursor at the last key/value pair in the database,
        /// and returns that pair.
        ///
        /// This corresponds to the `mdb_cursor_get` function with the
        /// `MDB_LAST` operation.
        ///
        /// ## Example
        ///
        /// ```
        /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
        /// # fn main() {
        /// # let env = create_env();
        /// # let db = dupdb(&env);
        /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
        /// {
        ///   let mut access = txn.access();
        ///   let f = lmdb::put::Flags::empty();
        ///   access.put(&db, "Germany", "Berlin", f).unwrap();
        ///   access.put(&db, "France", "Paris", f).unwrap();
        ///   access.put(&db, "Latvia", "Rīga", f).unwrap();
        ///
        ///   let mut cursor = txn.cursor(&db).unwrap();
        ///   assert_eq!(("Latvia", "Rīga"), cursor.last(&access).unwrap());
        /// }
        /// txn.commit().unwrap();
        /// # }
        /// ```
        fn last, ffi::MDB_cursor_op::MDB_LAST
    }

    cursor_get_0_v! {
        /// Positions the cursor at the last key/value pair whose key is equal
        /// to the current key.
        ///
        /// This only makes sense on `DUPSORT` databases.
        ///
        /// This correspnods to the `mdb_cursor_get` function with the
        /// `MDB_LAST_DUP` operation.
        ///
        /// ## Example
        ///
        /// ```
        /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
        /// # fn main() {
        /// # let env = create_env();
        /// # let db = dupdb(&env);
        /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
        /// {
        ///   let mut access = txn.access();
        ///   let f = lmdb::put::Flags::empty();
        ///   access.put(&db, "Fruit", "Apple", f).unwrap();
        ///   access.put(&db, "Fruit", "Orange", f).unwrap();
        ///   access.put(&db, "Fruit", "Durian", f).unwrap();
        ///   access.put(&db, "Animal", "Badger", f).unwrap();
        ///   access.put(&db, "Veggie", "Carrot", f).unwrap();
        ///
        ///   let mut cursor = txn.cursor(&db).unwrap();
        ///   assert_eq!("Apple", cursor.seek_k::<str,str>(&access, "Fruit").unwrap());
        ///   assert_eq!("Orange", cursor.last_dup::<str>(&access).unwrap());
        /// }
        /// txn.commit().unwrap();
        /// # }
        /// ```
        fn last_dup, ffi::MDB_cursor_op::MDB_LAST_DUP
    }

    cursor_get_0_kv! {
        /// Advances the cursor to the key/value pair following this one.
        ///
        /// If the current key has multiple values, this will remain on the
        /// same key unless it is already on the last value.
        ///
        /// This corresponds to the `mdb_cursor_get` function with the
        /// `MDB_NEXT` operation.
        ///
        /// ## Example
        ///
        /// ```
        /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
        /// # fn main() {
        /// # let env = create_env();
        /// # let db = dupdb(&env);
        /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
        /// {
        ///   let mut access = txn.access();
        ///   let f = lmdb::put::Flags::empty();
        ///   access.put(&db, "Fruit", "Apple", f).unwrap();
        ///   access.put(&db, "Fruit", "Orange", f).unwrap();
        ///   access.put(&db, "Animal", "Badger", f).unwrap();
        ///   access.put(&db, "Veggie", "Carrot", f).unwrap();
        ///
        ///   let mut cursor = txn.cursor(&db).unwrap();
        ///   assert_eq!(("Animal", "Badger"), cursor.first(&access).unwrap());
        ///   assert_eq!(("Fruit", "Apple"), cursor.next(&access).unwrap());
        ///   assert_eq!(("Fruit", "Orange"), cursor.next(&access).unwrap());
        ///   assert_eq!(("Veggie", "Carrot"), cursor.next(&access).unwrap());
        ///   assert!(cursor.next::<str,str>(&access).is_err());
        /// }
        /// txn.commit().unwrap();
        /// # }
        /// ```
        fn next, ffi::MDB_cursor_op::MDB_NEXT
    }

    cursor_get_0_kv! {
        /// Advances the cursor to the next value in the current key.
        ///
        /// This only makes sense on `DUPSORT` databases. This call fails if
        /// there are no more values in the current key.
        ///
        /// This corresponds to the `mdb_cursor_get` function with the
        /// `MDB_NEXT_DUP` operation.
        ///
        /// ## Example
        ///
        /// ```
        /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
        /// # fn main() {
        /// # let env = create_env();
        /// # let db = dupdb(&env);
        /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
        /// {
        ///   let mut access = txn.access();
        ///   let f = lmdb::put::Flags::empty();
        ///   access.put(&db, "Fruit", "Apple", f).unwrap();
        ///   access.put(&db, "Fruit", "Orange", f).unwrap();
        ///   access.put(&db, "Animal", "Badger", f).unwrap();
        ///   access.put(&db, "Veggie", "Carrot", f).unwrap();
        ///
        ///   let mut cursor = txn.cursor(&db).unwrap();
        ///   assert_eq!("Apple", cursor.seek_k::<str,str>(&access, "Fruit").unwrap());
        ///   assert_eq!(("Fruit", "Orange"), cursor.next_dup(&access).unwrap());
        ///   assert!(cursor.next_dup::<str,str>(&access).is_err());
        /// }
        /// txn.commit().unwrap();
        /// # }
        /// ```
        fn next_dup, ffi::MDB_cursor_op::MDB_NEXT_DUP
    }

    cursor_get_0_kv! {
        /// Advances the cursor to the first item of the key following the
        /// current key.
        ///
        /// This is permitted in all databases, but only behaves distinctly
        /// from `next()` in `DUPSORT` databases.
        ///
        /// This corresponds to the `mdb_cursor_get` function with the
        /// `MDB_NEXT_NODUP` operation.
        ///
        /// ## Example
        ///
        /// ```
        /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
        /// # fn main() {
        /// # let env = create_env();
        /// # let db = dupdb(&env);
        /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
        /// {
        ///   let mut access = txn.access();
        ///   let f = lmdb::put::Flags::empty();
        ///   access.put(&db, "Fruit", "Apple", f).unwrap();
        ///   access.put(&db, "Fruit", "Orange", f).unwrap();
        ///   access.put(&db, "Animal", "Badger", f).unwrap();
        ///   access.put(&db, "Veggie", "Carrot", f).unwrap();
        ///
        ///   let mut cursor = txn.cursor(&db).unwrap();
        ///   assert_eq!(("Animal", "Badger"), cursor.first(&access).unwrap());
        ///   assert_eq!(("Fruit", "Apple"), cursor.next_nodup(&access).unwrap());
        ///   assert_eq!(("Veggie", "Carrot"), cursor.next_nodup(&access).unwrap());
        ///   assert!(cursor.next_nodup::<str,str>(&access).is_err());
        /// }
        /// txn.commit().unwrap();
        /// # }
        /// ```
        fn next_nodup, ffi::MDB_cursor_op::MDB_NEXT_NODUP
    }

    cursor_get_0_kv! {
        /// Retreats the cursor to the previous key/value pair.
        ///
        /// If the current key has multiple values, this will remain on the
        /// same key unless it is already on the first value.
        ///
        /// This corresponds to the `mdb_cursor_get` function with the
        /// `MDB_PREV` operation.
        ///
        /// ## Example
        ///
        /// ```
        /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
        /// # fn main() {
        /// # let env = create_env();
        /// # let db = dupdb(&env);
        /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
        /// {
        ///   let mut access = txn.access();
        ///   let f = lmdb::put::Flags::empty();
        ///   access.put(&db, "Fruit", "Apple", f).unwrap();
        ///   access.put(&db, "Fruit", "Orange", f).unwrap();
        ///   access.put(&db, "Animal", "Badger", f).unwrap();
        ///   access.put(&db, "Veggie", "Carrot", f).unwrap();
        ///
        ///   let mut cursor = txn.cursor(&db).unwrap();
        ///   assert_eq!(("Veggie", "Carrot"), cursor.last(&access).unwrap());
        ///   assert_eq!(("Fruit", "Orange"), cursor.prev(&access).unwrap());
        ///   assert_eq!(("Fruit", "Apple"), cursor.prev(&access).unwrap());
        ///   assert_eq!(("Animal", "Badger"), cursor.prev(&access).unwrap());
        ///   assert!(cursor.prev::<str,str>(&access).is_err());
        /// }
        /// txn.commit().unwrap();
        /// # }
        /// ```
        fn prev, ffi::MDB_cursor_op::MDB_PREV
    }

    cursor_get_0_kv! {
        /// Retreats the cursor to the previous value in the current key.
        ///
        /// This only makes sense on `DUPSORT` databases. This call fails if
        /// there are no prior values in the current key.
        ///
        /// This corresponds to the `mdb_cursor_get` function with the
        /// `MDB_PREV_DUP` operation.
        ///
        /// ## Example
        ///
        /// ```
        /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
        /// # fn main() {
        /// # let env = create_env();
        /// # let db = dupdb(&env);
        /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
        /// {
        ///   let mut access = txn.access();
        ///   let f = lmdb::put::Flags::empty();
        ///   access.put(&db, "Fruit", "Apple", f).unwrap();
        ///   access.put(&db, "Fruit", "Orange", f).unwrap();
        ///   access.put(&db, "Animal", "Badger", f).unwrap();
        ///   access.put(&db, "Veggie", "Carrot", f).unwrap();
        ///
        ///   let mut cursor = txn.cursor(&db).unwrap();
        ///   assert_eq!("Apple", cursor.seek_k::<str,str>(&access, "Fruit").unwrap());
        ///   assert_eq!(("Fruit", "Orange"), cursor.next_dup(&access).unwrap());
        ///   assert_eq!(("Fruit", "Apple"), cursor.prev_dup(&access).unwrap());
        ///   assert!(cursor.prev_dup::<str,str>(&access).is_err());
        /// }
        /// txn.commit().unwrap();
        /// # }
        /// ```
        fn prev_dup, ffi::MDB_cursor_op::MDB_PREV_DUP
    }

    cursor_get_0_kv! {
        /// Retreats the cursor to the final item of the previous key.
        ///
        /// This is permitted in all databases, but only behaves distinctly
        /// from `prev()` in `DUPSORT` databases.
        ///
        /// This corresponds to the `mdb_cursor_get` function with the
        /// `MDB_PREV_NODUP` operation.
        ///
        /// ## Example
        ///
        /// ```
        /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
        /// # fn main() {
        /// # let env = create_env();
        /// # let db = dupdb(&env);
        /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
        /// {
        ///   let mut access = txn.access();
        ///   let f = lmdb::put::Flags::empty();
        ///   access.put(&db, "Fruit", "Apple", f).unwrap();
        ///   access.put(&db, "Fruit", "Orange", f).unwrap();
        ///   access.put(&db, "Animal", "Badger", f).unwrap();
        ///   access.put(&db, "Veggie", "Carrot", f).unwrap();
        ///
        ///   let mut cursor = txn.cursor(&db).unwrap();
        ///   assert_eq!(("Veggie", "Carrot"), cursor.last(&access).unwrap());
        ///   assert_eq!(("Fruit", "Orange"), cursor.prev_nodup(&access).unwrap());
        ///   assert_eq!(("Animal", "Badger"), cursor.prev_nodup(&access).unwrap());
        ///   assert!(cursor.prev_nodup::<str,str>(&access).is_err());
        /// }
        /// txn.commit().unwrap();
        /// # }
        /// ```
        fn prev_nodup, ffi::MDB_cursor_op::MDB_PREV_NODUP
    }

    /// Positions the cursor at the first item of the given key.
    ///
    /// Returns the value of that item.
    ///
    /// This corresponds to the `mdb_cursor_get` function with the `MDB_SET`
    /// operation.
    ///
    /// ## Example
    ///
    /// ```
    /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
    /// # fn main() {
    /// # let env = create_env();
    /// # let db = dupdb(&env);
    /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
    /// {
    ///   let mut access = txn.access();
    ///   let f = lmdb::put::Flags::empty();
    ///   access.put(&db, "Fruit", "Apple", f).unwrap();
    ///   access.put(&db, "Fruit", "Orange", f).unwrap();
    ///   access.put(&db, "Animal", "Badger", f).unwrap();
    ///   access.put(&db, "Veggie", "Carrot", f).unwrap();
    ///
    ///   let mut cursor = txn.cursor(&db).unwrap();
    ///   assert_eq!("Apple", cursor.seek_k::<str,str>(&access, "Fruit").unwrap());
    /// }
    /// txn.commit().unwrap();
    /// # }
    /// ```
    #[inline]
    pub fn seek_k<'access, K : AsLmdbBytes + ?Sized,
                  V : FromLmdbBytes + ?Sized>
        (&mut self, access: &'access ConstAccessor, key: &K)
        -> Result<&'access V>
    {
        self.get_k_v(access, key, ffi::MDB_cursor_op::MDB_SET)
    }

    /// Positions the cursor at the first item of the given key.
    ///
    /// Returns the key and value of that item.
    ///
    /// This corresponds to the `mdb_cursor_get` function with the
    /// `MDB_SET_KEY` operation.
    ///
    /// ## Example
    ///
    /// ```
    /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
    /// # fn main() {
    /// # let env = create_env();
    /// # let db = dupdb(&env);
    /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
    /// {
    ///   let mut access = txn.access();
    ///   let f = lmdb::put::Flags::empty();
    ///   access.put(&db, "Fruit", "Apple", f).unwrap();
    ///   access.put(&db, "Fruit", "Orange", f).unwrap();
    ///   access.put(&db, "Animal", "Badger", f).unwrap();
    ///   access.put(&db, "Veggie", "Carrot", f).unwrap();
    ///
    ///   let mut cursor = txn.cursor(&db).unwrap();
    ///   assert_eq!(("Fruit", "Apple"), cursor.seek_k_both(&access, "Fruit").unwrap());
    /// }
    /// txn.commit().unwrap();
    /// # }
    /// ```
    #[inline]
    pub fn seek_k_both<'access, K : AsLmdbBytes + FromLmdbBytes + ?Sized,
                       V : FromLmdbBytes + ?Sized>
        (&mut self, access: &'access ConstAccessor, key: &K)
         -> Result<(&'access K, &'access V)>
    {
        self.get_k_kv(access, key, ffi::MDB_cursor_op::MDB_SET_KEY)
    }

    /// Positions the cursor at the first item whose key is greater than or
    /// equal to `key`.
    ///
    /// Return the key and value of that item.
    ///
    /// This corresponds to the `mdb_cursor_get` function with the
    /// `MDB_SET_RANGE` operation.
    ///
    /// ## Example
    ///
    /// ```
    /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
    /// # fn main() {
    /// # let env = create_env();
    /// # let db = dupdb(&env);
    /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
    /// {
    ///   let mut access = txn.access();
    ///   let f = lmdb::put::Flags::empty();
    ///   access.put(&db, "Fruit", "Apple", f).unwrap();
    ///   access.put(&db, "Fruit", "Orange", f).unwrap();
    ///   access.put(&db, "Animal", "Badger", f).unwrap();
    ///
    ///   let mut cursor = txn.cursor(&db).unwrap();
    ///   assert_eq!(("Fruit", "Apple"), cursor.seek_range_k(&access, "Fog").unwrap());
    ///   assert!(cursor.seek_range_k::<str,str>(&access, "Veggie").is_err());
    /// }
    /// txn.commit().unwrap();
    /// # }
    /// ```
    #[inline]
    pub fn seek_range_k<'access, K : AsLmdbBytes + FromLmdbBytes + ?Sized,
                        V : FromLmdbBytes + ?Sized>
        (&mut self, access: &'access ConstAccessor, key: &K)
         -> Result<(&'access K, &'access V)>
    {
        self.get_k_kv(access, key, ffi::MDB_cursor_op::MDB_SET_RANGE)
    }

    /// Writes a single value through this cursor.
    ///
    /// By default, any item with the same key (if not `DUPSORT`) or any
    /// exactly matching item (if `DUPSORT`) is replaced silently. `flags` can
    /// be used to override this.
    ///
    /// This does not inherently overwrite the current item. See `overwrite()`
    /// for that.
    ///
    /// The cursor is positioned at the new item, or on failure usually near
    /// it.
    ///
    /// ## Example
    ///
    /// ```
    /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
    /// # fn main() {
    /// # let env = create_env();
    /// # let db = dupdb(&env);
    /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
    /// {
    ///   let mut access = txn.access();
    ///   let f = lmdb::put::Flags::empty();
    ///   let mut cursor = txn.cursor(&db).unwrap();
    ///   cursor.put(&mut access, "Germany", "Berlin", f).unwrap();
    ///   assert_eq!(("Germany", "Berlin"), cursor.get_current(&access).unwrap());
    /// }
    /// txn.commit().unwrap();
    /// # }
    /// ```
    #[inline]
    pub fn put<K : AsLmdbBytes + ?Sized, V : AsLmdbBytes + ?Sized>
        (&mut self, access: &mut WriteAccessor,
         key: &K, val: &V, flags: put::Flags) -> Result<()>
    {
        try!(assert_sensible_cursor(&*access, self));

        let mut mv_key = as_val(key);
        let mut mv_val = as_val(val);

        unsafe {
            lmdb_call!(ffi::mdb_cursor_put(
                self.cursor.0, &mut mv_key, &mut mv_val,
                flags.bits()));
        }

        Ok(())
    }

    /// Overwrites the current item referenced by the cursor.
    ///
    /// `key` must match the key of the current item. If the database is
    /// `DUPSORT`, `val` must still sort into the same position relative to the
    /// other items with the same key.
    ///
    /// This is intended to be used when the new data is the same size as the
    /// old. Otherwise it will simply perform a delete of the old record
    /// followed by an insert.
    ///
    /// The cursor is positioned at the new item, or on failure usually near
    /// it.
    ///
    /// ## Example
    ///
    /// ```
    /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
    /// # fn main() {
    /// # let env = create_env();
    /// # let db = defdb(&env);
    /// use lmdb::unaligned as u;
    ///
    /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
    /// {
    ///   let mut access = txn.access();
    ///   let f = lmdb::put::Flags::empty();
    ///   let mut cursor = txn.cursor(&db).unwrap();
    ///   cursor.put(&mut access, "Fourty-two", &42u32, f).unwrap();
    ///   cursor.overwrite(&mut access, "Fourty-two", &54u32, f).unwrap();
    ///   assert_eq!(("Fourty-two", u(&54u32)),
    ///              cursor.get_current(&access).unwrap());
    /// }
    /// txn.commit().unwrap();
    /// # }
    /// ```
    #[inline]
    pub fn overwrite<K : AsLmdbBytes + ?Sized, V : AsLmdbBytes + ?Sized>
        (&mut self, access: &mut WriteAccessor,
         key: &K, val: &V, flags: put::Flags) -> Result<()>
    {
        try!(assert_sensible_cursor(&*access, self));

        let mut mv_key = as_val(key);
        let mut mv_val = as_val(val);

        unsafe {
            lmdb_call!(ffi::mdb_cursor_put(
                self.cursor.0, &mut mv_key, &mut mv_val,
                flags.bits() | ffi::MDB_CURRENT));
        }

        Ok(())
    }

    /// Reserves space for an entry with the given key and returns a pointer to
    /// that entry.
    ///
    /// The size of the entry is simply the size of `V`.
    ///
    /// This cannot be used on a `DUPSORT` database.
    ///
    /// The cursor is positioned at the new item, or on failure usually near
    /// it.
    ///
    /// ## Example
    ///
    /// ```
    /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
    /// #[repr(C, packed)]
    /// #[derive(Clone,Copy,Debug,PartialEq,Eq)]
    /// struct MyStruct {
    ///   x: i32,
    ///   y: i32,
    /// }
    /// unsafe impl lmdb::traits::LmdbRaw for MyStruct { }
    ///
    /// # fn main() {
    /// # let env = create_env();
    /// # let db = defdb(&env);
    /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
    /// {
    ///   let mut access = txn.access();
    ///   let f = lmdb::put::Flags::empty();
    ///   let mut cursor = txn.cursor(&db).unwrap();
    ///   {
    ///     let v: &mut MyStruct = cursor.reserve(&mut access, "foo", f).unwrap();
    ///     // Write directly into the database
    ///     v.x = 42;
    ///     v.y = 56;
    ///   }
    ///
    ///   assert_eq!(("foo", &MyStruct { x: 42, y: 56 }),
    ///              cursor.get_current(&access).unwrap());
    /// }
    /// txn.commit().unwrap();
    /// # }
    /// ```
    #[inline]
    pub fn reserve<'access, K : AsLmdbBytes + ?Sized,
                   V : FromReservedLmdbBytes + Sized>
        (&mut self, access: &'access mut WriteAccessor,
         key: &K, flags: put::Flags) -> Result<&'access mut V>
    {
        unsafe {
            self.reserve_unsized(access, key, mem::size_of::<V>(), flags)
        }
    }

    /// Reserves space for an entry with the given key and returns a pointer to
    /// an array of values backing that entry.
    ///
    /// The size of the entry is simply the size of `V` times the desired
    /// number of elements.
    ///
    /// This cannot be used on a `DUPSORT` database. (Do not confuse with
    /// `put_multiple`, which does support `DUPSORT` but is not zero-copy.)
    ///
    /// The cursor is positioned at the new item, or on failure usually near
    /// it.
    ///
    /// ## Example
    ///
    /// ```
    /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
    /// #[repr(C, packed)]
    /// #[derive(Clone,Copy,Debug,PartialEq,Eq)]
    /// struct MyStruct {
    ///   x: i32,
    ///   y: i32,
    /// }
    /// unsafe impl lmdb::traits::LmdbRaw for MyStruct { }
    ///
    /// # fn main() {
    /// # let env = create_env();
    /// # let db = defdb(&env);
    /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
    /// {
    ///   let mut access = txn.access();
    ///   let f = lmdb::put::Flags::empty();
    ///   let mut cursor = txn.cursor(&db).unwrap();
    ///   {
    ///     let v: &mut [u8] = cursor.reserve_array(&mut access, "foo", 4, f).unwrap();
    ///     // Write directly into the database
    ///     v[0] = b'b'; v[1] = b'y'; v[2] = b't'; v[3] = b'e';
    ///   }
    ///
    ///   assert_eq!(("foo", "byte"), cursor.get_current(&access).unwrap());
    /// }
    /// txn.commit().unwrap();
    /// # }
    /// ```
    #[inline]
    pub fn reserve_array<'access, K : AsLmdbBytes + ?Sized,
                         V : LmdbRaw>
        (&mut self, access: &'access mut WriteAccessor,
         key: &K, count: usize, flags: put::Flags)
         -> Result<&'access mut [V]>
    {
        unsafe {
            self.reserve_unsized(
                access, key, count * mem::size_of::<V>(), flags)
        }
    }

    /// Reserves space for an entry with the given key and returns a pointer to
    /// that entry.
    ///
    /// This cannot be used on a `DUPSORT` database.
    ///
    /// The cursor is positioned at the new item, or on failure usually near
    /// it.
    ///
    /// ## Unsafety
    ///
    /// The caller must ensure that `size` is a valid size for `V`.
    pub unsafe fn reserve_unsized<'access, K : AsLmdbBytes + ?Sized,
                                  V : FromReservedLmdbBytes + ?Sized>
        (&mut self, access: &'access mut WriteAccessor,
         key: &K, size: usize, flags: put::Flags) -> Result<&'access mut V>
    {
        try!(assert_sensible_cursor(&*access, self));

        let mut mv_key = as_val(key);
        let mut out_val = EMPTY_VAL;
        out_val.mv_size = size;

        lmdb_call!(ffi::mdb_cursor_put(
            self.cursor.0, &mut mv_key, &mut out_val,
            flags.bits() | ffi::MDB_RESERVE));

        Ok(from_reserved(access, &out_val))
    }

    /// Returns a writable reference to the value belonging to the given key in
    /// the database.
    ///
    /// This has all the caveats of both `overwrite()` and `reserve()`.
    ///
    /// ## Updating by mutation
    ///
    /// It is possible to use this call to perform a read-modify-write
    /// operation on the data in the database, provided you are certain that
    /// the value exists with the exact size of `V`, for example if you just
    /// read the value as a `V` using something that requires a particular size
    /// (such as `LmdbRaw`).
    ///
    /// ## Example
    ///
    /// ```
    /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
    /// # fn main() {
    /// # let env = create_env();
    /// # let db = defdb(&env);
    /// use lmdb::Unaligned as U;
    /// use lmdb::unaligned as u;
    ///
    /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
    /// {
    ///   let mut access = txn.access();
    ///   let f = lmdb::put::Flags::empty();
    ///   let mut cursor = txn.cursor(&db).unwrap();
    ///   cursor.put(&mut access, "count", &1u32, f).unwrap();
    ///   {
    ///     let count: &mut U<u32> = cursor.overwrite_in_place(
    ///       &mut access, "count", f).unwrap();
    ///     // Directly edit the value in the database
    ///     let count2 = count.get() + 1;
    ///     count.set(count2);
    ///   }
    ///   assert_eq!(("count", u(&2u32)), cursor.get_current(&access).unwrap());
    /// }
    /// txn.commit().unwrap();
    /// # }
    /// ```
    #[inline]
    pub fn overwrite_in_place<'access, K : AsLmdbBytes + ?Sized,
                              V : FromReservedLmdbBytes + Sized>
        (&mut self, access: &'access mut WriteAccessor,
         key: &K, flags: put::Flags) -> Result<&'access mut V>
    {
        unsafe {
            self.overwrite_in_place_unsized(
                access, key, mem::size_of::<V>(), flags)
        }
    }

    /// Returns a writable reference to the array of values belonging to the
    /// given key in the database.
    ///
    /// This has all the caveats of both `overwrite()` and `reserve_array()`.
    ///
    /// ## Updating by mutation
    ///
    /// It is possible to use this call to perform a read-modify-write
    /// operation on the data in the database, provided you are certain that
    /// the value exists with the exact size of `V` times `count`.
    ///
    /// ## Example
    ///
    /// ```
    /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
    /// # fn main() {
    /// # let env = create_env();
    /// # let db = defdb(&env);
    /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
    /// {
    ///   let mut access = txn.access();
    ///   let f = lmdb::put::Flags::empty();
    ///   let mut cursor = txn.cursor(&db).unwrap();
    ///   cursor.put(&mut access, "foo", "bar", f).unwrap();
    ///   {
    ///     let data: &mut [u8] = cursor.overwrite_in_place_array(
    ///       &mut access, "foo", 3, f).unwrap();
    ///     // Directly edit the value in the database
    ///     data[2] = b'z';
    ///   }
    ///   assert_eq!(("foo", "baz"), cursor.get_current(&access).unwrap());
    /// }
    /// txn.commit().unwrap();
    /// # }
    /// ```
    #[inline]
    pub fn overwrite_in_place_array<'access, K : AsLmdbBytes + ?Sized,
                                    V : LmdbRaw>
        (&mut self, access: &'access mut WriteAccessor,
         key: &K, count: usize, flags: put::Flags)
         -> Result<&'access mut [V]>
    {
        unsafe {
            self.overwrite_in_place_unsized(
                access, key, count * mem::size_of::<V>(), flags)
        }
    }

    /// Returns a writable reference to the value belonging to the given key in
    /// the database.
    ///
    /// This has all the caveats of both `overwrite()` and `reserve_unsized()`.
    ///
    /// ## Unsafety
    ///
    /// The caller must ensure `size` is a valid size of `V`.
    pub unsafe fn overwrite_in_place_unsized
        <'access, K : AsLmdbBytes + ?Sized, V : FromReservedLmdbBytes + ?Sized>
        (&mut self, access: &'access mut WriteAccessor,
         key: &K, size: usize, flags: put::Flags) -> Result<&'access mut V>
    {
        try!(assert_sensible_cursor(&*access, self));

        let mut mv_key = as_val(key);
        let mut out_val = EMPTY_VAL;
        out_val.mv_size = size;

        lmdb_call!(ffi::mdb_cursor_put(
            self.cursor.0, &mut mv_key, &mut out_val,
            flags.bits() | ffi::MDB_RESERVE | ffi::MDB_CURRENT));

        Ok(from_reserved(access, &out_val))
    }

    /// Stores multiple data elements with the same key in a single request.
    ///
    /// This is only permitted for `DUPFIXED` databases.
    ///
    /// Note that `values` must be a slice of `LmdbRaw`, since this function
    /// needs to know the exact size of each individual item and must be able
    /// to directly reinterpret the slice as a byte array.
    ///
    /// On success, returns the number of items that were actually written.
    ///
    /// ## Warning
    ///
    /// `MDB_MULTIPLE` has historically been rather problematic. Using this
    /// function may result in erratic behaviour on many versions of LMDB.
    ///
    /// ## Example
    ///
    /// ```
    /// # include!(concat!(env!("CARGO_MANIFEST_DIR"),"/src/example_helpers.rs"));
    /// # fn main() {
    /// # let env = create_env();
    /// # let db = dupfixeddb(&env);
    /// use lmdb::Unaligned as U;
    /// use lmdb::unaligned as u;
    ///
    /// let txn = lmdb::WriteTransaction::new(&env).unwrap();
    /// {
    ///   let mut access = txn.access();
    ///   let f = lmdb::put::Flags::empty();
    ///   let mut cursor = txn.cursor(&db).unwrap();
    ///   // XXX Whether this is supposed to be 4 or 3 is unclear.
    ///   assert_eq!(4, cursor.put_multiple(
    ///     &mut access, "bar", &[U::new(0u32), U::new(1u32),
    ///                           U::new(2u32), U::new(1u32)], f).unwrap());
    /// # // XXX I wanted a lot more assertions here, but I kept running into
    /// # // issues that I think but am not sure are bugs.
    ///
    ///   assert_eq!(("bar", u(&0u32)), cursor.first(&access).unwrap());
    ///   assert_eq!(("bar", u(&1u32)), cursor.next(&access).unwrap());
    ///   assert_eq!(("bar", u(&2u32)), cursor.next(&access).unwrap());
    ///   assert!(cursor.next::<str,U<u32>>(&access).is_err());
    /// }
    /// txn.commit().unwrap();
    /// # }
    /// ```
    pub fn put_multiple<K : AsLmdbBytes + ?Sized, V : LmdbRaw>
        (&mut self, access: &mut WriteAccessor,
         key: &K, values: &[V], flags: put::Flags)
         -> Result<usize>
    {
        try!(assert_sensible_cursor(&*access, self));

        // Some LMDB versions didn't (don't?) handle count=0 correctly
        if values.is_empty() {
            return Ok(0);
        }

        let mut mv_key = as_val(key);
        let mut mv_vals = [ ffi::MDB_val {
            mv_size: mem::size_of::<V>() as libc::size_t,
            mv_data: values.as_lmdb_bytes().as_ptr() as *mut c_void,
        }, ffi::MDB_val {
            mv_size: values.len() as libc::size_t,
            mv_data: ptr::null_mut(),
        }];

        unsafe {
            lmdb_call!(ffi::mdb_cursor_put(
                self.cursor.0, &mut mv_key, mv_vals.as_mut_ptr(),
                flags.bits() | ffi::MDB_MULTIPLE));
        }

        Ok(mv_vals[1].mv_size as usize)
    }

    /// Delete current key/value pair.
    ///
    /// By default, this deletes only the current pair. `flags` can be set to
    /// `NODUPDATA` for `DUPDATA` databases to delete everything with the
    /// current key.
    ///
    /// See `lmdb_zero::del::NODUPDATA` for examples on how `flags` can be used
    /// to control behaviour.
    #[inline]
    pub fn del(&mut self, access: &mut WriteAccessor,
               flags: del::Flags) -> Result<()> {
        try!(assert_sensible_cursor(&*access, self));

        unsafe {
            lmdb_call!(ffi::mdb_cursor_del(self.cursor.0, flags.bits()));
        }

        Ok(())
    }

    /// Return count of duplicates for current key.
    ///
    /// This call is only valid on `DUPSORT` databases.
    #[inline]
    pub fn count(&mut self) -> Result<usize> {
        let mut raw: libc::size_t = 0;
        unsafe {
            lmdb_call!(ffi::mdb_cursor_count(self.cursor.0, &mut raw));
        }
        Ok(raw as usize)
    }
}

#[cfg(test)]
mod test {
    use dbi::{db, Database, DatabaseOptions};
    use error::LmdbResultExt;
    use tx::{put, WriteTransaction};
    use test_helpers::*;
    use unaligned::Unaligned as U;
    use unaligned::unaligned;

    #[test]
    fn get_multiple_with_one_item() {
        let env = create_env();
        let db = Database::open(
            &env, None, &DatabaseOptions::new(
                db::DUPSORT | db::INTEGERKEY | db::DUPFIXED | db::INTEGERDUP |
                db::CREATE)).unwrap();
        let txn = WriteTransaction::new(&env).unwrap();
        {
            let key: i32 = 42;
            let val: i32 = 56;

            let mut access = txn.access();
            access.put(&db, &key, &val, put::Flags::empty()).unwrap();

            let mut cursor = txn.cursor(&db).unwrap();
            cursor.seek_k::<U<i32>, U<i32>>(&access, unaligned(&key)).unwrap();
            let vals = cursor.get_multiple::<[U<i32>]>(&access).unwrap();
            assert_eq!(1, vals.len());
            assert_eq!(val, vals[0].get());

            assert!(cursor.next_multiple::<[U<i32>]>(&access)
                    .to_opt().unwrap().is_none());
        }
    }
}