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
//! `WriteBatch` holds a collection of updates to apply atomically to a DB.
//!
//! The updates are applied in the order in which they are added
//! to the WriteBatch.  For example, the value of "key" will be "v3"
//! after the following batch is written:
//!
//!    batch.Put("key", "v1");
//!    batch.Delete("key");
//!    batch.Put("key", "v2");
//!    batch.Put("key", "v3");
//!
//! Multiple threads can invoke const methods on a WriteBatch without
//! external synchronization, but if any of the threads may call a
//! non-const method, all threads accessing the same WriteBatch must use
//! external synchronization.

use std::fmt;
use std::os::raw::{c_uchar, c_void};
use std::ptr;
use std::slice;

use rocks_sys as ll;

use crate::db::ColumnFamilyHandle;
use crate::to_raw::{FromRaw, ToRaw};
use crate::{Error, Result};

/// `WriteBatch` holds a collection of updates to apply atomically to a DB.
pub struct WriteBatch {
    raw: *mut ll::rocks_writebatch_t,
}

unsafe impl Sync for WriteBatch {}
unsafe impl Send for WriteBatch {}

impl Drop for WriteBatch {
    fn drop(&mut self) {
        unsafe { ll::rocks_writebatch_destroy(self.raw) }
    }
}

impl Clone for WriteBatch {
    fn clone(&self) -> Self {
        WriteBatch {
            raw: unsafe { ll::rocks_writebatch_copy(self.raw) },
        }
    }
}

impl fmt::Debug for WriteBatch {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("WriteBatch")
            .field("items", &self.count())
            .field("data_size", &self.get_data_size())
            .finish()
    }
}

// FIXME: this is directly converted to raw pointer, not the rocks wrapped
impl ToRaw<ll::rocks_raw_writebatch_t> for WriteBatch {
    fn raw(&self) -> *mut ll::rocks_raw_writebatch_t {
        unsafe { ll::rocks_writebatch_get_writebatch(self.raw) }
    }
}

impl FromRaw<ll::rocks_writebatch_t> for WriteBatch {
    unsafe fn from_ll(raw: *mut ll::rocks_writebatch_t) -> WriteBatch {
        WriteBatch { raw: raw }
    }
}

impl Default for WriteBatch {
    fn default() -> Self {
        WriteBatch::new()
    }
}

impl WriteBatch {
    pub fn new() -> WriteBatch {
        WriteBatch {
            raw: unsafe { ll::rocks_writebatch_create() },
        }
    }

    pub fn with_reserved_bytes(reserved_bytes: usize) -> WriteBatch {
        WriteBatch {
            raw: unsafe { ll::rocks_writebatch_create_with_reserved_bytes(reserved_bytes) },
        }
    }

    /// Clear all updates buffered in this batch.
    pub fn clear(&mut self) {
        unsafe {
            ll::rocks_writebatch_clear(self.raw);
        }
    }

    /// Store the mapping "key->value" in the database.
    pub fn put(&mut self, key: &[u8], value: &[u8]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_put(self.raw, key.as_ptr() as _, key.len(), value.as_ptr() as _, value.len());
        }
        self
    }

    pub fn put_cf(&mut self, column_family: &ColumnFamilyHandle, key: &[u8], value: &[u8]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_put_cf(
                self.raw,
                column_family.raw(),
                key.as_ptr() as _,
                key.len(),
                value.as_ptr() as _,
                value.len(),
            );
        }
        self
    }

    /// Variant of Put() that gathers output like writev(2).  The key and value
    /// that will be written to the database are concatentations of arrays of
    /// slices.
    pub fn putv(&mut self, key: &[&[u8]], value: &[&[u8]]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_putv_coerce(
                self.raw,
                key.as_ptr() as _,
                key.len() as _,
                value.as_ptr() as _,
                value.len() as _,
            )
        }
        self
    }

    pub fn putv_cf(&mut self, column_family: &ColumnFamilyHandle, key: &[&[u8]], value: &[&[u8]]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_putv_cf_coerce(
                self.raw,
                column_family.raw(),
                key.as_ptr() as _,
                key.len() as _,
                value.as_ptr() as _,
                value.len() as _,
            )
        }
        self
    }

    /// If the database contains a mapping for "key", erase it.  Else do nothing.
    pub fn delete(&mut self, key: &[u8]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_delete(self.raw, key.as_ptr() as _, key.len());
        }
        self
    }

    pub fn delete_cf(&mut self, column_family: &ColumnFamilyHandle, key: &[u8]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_delete_cf(self.raw, column_family.raw(), key.as_ptr() as _, key.len());
        }
        self
    }

    /// variant that takes SliceParts
    pub fn deletev(&mut self, key: &[&[u8]]) -> &mut Self {
        unsafe { ll::rocks_writebatch_deletev_coerce(self.raw, key.as_ptr() as _, key.len() as _) }
        self
    }

    pub fn deletev_cf(&mut self, column_family: &ColumnFamilyHandle, key: &[&[u8]]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_deletev_cf_coerce(self.raw, column_family.raw(), key.as_ptr() as _, key.len() as _)
        }
        self
    }

    /// WriteBatch implementation of DB::SingleDelete().  See db.h.
    pub fn single_delete(&mut self, key: &[u8]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_single_delete(self.raw, key.as_ptr() as _, key.len());
        }
        self
    }

    pub fn single_delete_cf(&mut self, column_family: &ColumnFamilyHandle, key: &[u8]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_single_delete_cf(self.raw, column_family.raw(), key.as_ptr() as _, key.len());
        }
        self
    }

    /// variant that takes SliceParts
    pub fn single_deletev(&mut self, key: &[&[u8]]) -> &mut Self {
        unsafe { ll::rocks_writebatch_single_deletev_coerce(self.raw, key.as_ptr() as _, key.len() as _) }
        self
    }

    pub fn single_deletev_cf(&mut self, column_family: &ColumnFamilyHandle, key: &[&[u8]]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_single_deletev_cf_coerce(
                self.raw,
                column_family.raw(),
                key.as_ptr() as _,
                key.len() as _,
            )
        }
        self
    }

    /// WriteBatch implementation of DB::DeleteRange().  See db.h.
    pub fn delete_range(&mut self, begin_key: &[u8], end_key: &[u8]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_delete_range(
                self.raw,
                begin_key.as_ptr() as _,
                begin_key.len(),
                end_key.as_ptr() as _,
                end_key.len(),
            );
        }
        self
    }

    pub fn delete_range_cf(
        &mut self,
        column_family: &ColumnFamilyHandle,
        begin_key: &[u8],
        end_key: &[u8],
    ) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_delete_range_cf(
                self.raw,
                column_family.raw(),
                begin_key.as_ptr() as _,
                begin_key.len(),
                end_key.as_ptr() as _,
                end_key.len(),
            );
        }
        self
    }

    /// variant that takes SliceParts
    pub fn deletev_range(&mut self, begin_key: &[&[u8]], end_key: &[&[u8]]) -> &mut Self {
        unsafe {
            // NOTE: use nullptr to denote default column family
            ll::rocks_writebatch_deletev_range_cf_coerce(
                self.raw,
                ptr::null_mut(),
                begin_key.as_ptr() as _,
                begin_key.len() as _,
                end_key.as_ptr() as _,
                end_key.len() as _,
            );
        }
        self
    }

    pub fn deletev_range_cf(
        &mut self,
        column_family: &ColumnFamilyHandle,
        begin_key: &[&[u8]],
        end_key: &[&[u8]],
    ) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_deletev_range_cf_coerce(
                self.raw,
                column_family.raw(),
                begin_key.as_ptr() as _,
                begin_key.len() as _,
                end_key.as_ptr() as _,
                end_key.len() as _,
            );
        }
        self
    }

    /// Merge "value" with the existing value of "key" in the database.
    /// "key->merge(existing, value)"
    pub fn merge(&mut self, key: &[u8], value: &[u8]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_merge(self.raw, key.as_ptr() as _, key.len(), value.as_ptr() as _, value.len());
        }
        self
    }

    pub fn merge_cf(&mut self, column_family: &ColumnFamilyHandle, key: &[u8], value: &[u8]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_merge_cf(
                self.raw,
                column_family.raw(),
                key.as_ptr() as _,
                key.len(),
                value.as_ptr() as _,
                value.len(),
            );
        }
        self
    }

    // variant that takes SliceParts
    pub fn mergev(&mut self, key: &[&[u8]], value: &[&[u8]]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_mergev_coerce(
                self.raw,
                key.as_ptr() as _,
                key.len() as _,
                value.as_ptr() as _,
                value.len() as _,
            )
        }
        self
    }

    pub fn mergev_cf(&mut self, column_family: &ColumnFamilyHandle, key: &[&[u8]], value: &[&[u8]]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_mergev_cf_coerce(
                self.raw,
                column_family.raw(),
                key.as_ptr() as _,
                key.len() as _,
                value.as_ptr() as _,
                value.len() as _,
            )
        }
        self
    }

    /// Append a blob of arbitrary size to the records in this batch. The blob will
    /// be stored in the transaction log but not in any other file. In particular,
    /// it will not be persisted to the SST files. When iterating over this
    /// WriteBatch, WriteBatch::Handler::LogData will be called with the contents
    /// of the blob as it is encountered. Blobs, puts, deletes, and merges will be
    /// encountered in the same order in thich they were inserted. The blob will
    /// NOT consume sequence number(s) and will NOT increase the count of the batch
    ///
    /// Example application: add timestamps to the transaction log for use in
    /// replication.
    pub fn put_log_data(&mut self, blob: &[u8]) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_put_log_data(self.raw, blob.as_ptr() as _, blob.len());
        }
        self
    }

    /// Records the state of the batch for future calls to RollbackToSavePoint().
    /// May be called multiple times to set multiple save points.
    pub fn set_save_point(&mut self) -> &mut Self {
        unsafe {
            ll::rocks_writebatch_set_save_point(self.raw);
        }
        self
    }

    /// Remove all entries in this batch (Put, Merge, Delete, PutLogData) since the
    /// most recent call to SetSavePoint() and removes the most recent save point.
    /// If there is no previous call to SetSavePoint(), Status::NotFound()
    /// will be returned.
    /// Otherwise returns Status::OK().
    pub fn rollback_to_save_point(&mut self) -> Result<()> {
        let mut status = ptr::null_mut();
        unsafe {
            ll::rocks_writebatch_rollback_to_save_point(self.raw, &mut status);
            Error::from_ll(status)
        }
    }

    /// Pop the most recent save point.
    /// If there is no previous call to SetSavePoint(), Status::NotFound()
    /// will be returned.
    /// Otherwise returns Status::OK().
    pub fn pop_save_point(&mut self) -> Result<()> {
        let mut status = ptr::null_mut();
        unsafe {
            ll::rocks_writebatch_pop_save_point(self.raw, &mut status);
            Error::from_ll(status)
        }
    }

    /// Support for iterating over the contents of a batch.
    pub fn iterate<H: WriteBatchHandler>(&self, handler: &mut H) -> Result<()> {
        let mut status = ptr::null_mut();
        unsafe {
            // Box<&mut WriteBatchHandler>
            let raw_ptr = Box::into_raw(Box::new(handler as &mut dyn WriteBatchHandler)) as *mut c_void;
            ll::rocks_writebatch_iterate(self.raw, raw_ptr, &mut status);
            Error::from_ll(status)
        }
    }

    /// Retrieve the serialized version of this batch.
    pub fn get_data(&self) -> &[u8] {
        let mut size = 0;
        unsafe {
            let ptr = ll::rocks_writebatch_data(self.raw, &mut size);
            slice::from_raw_parts(ptr as *const _, size)
        }
    }

    // FIXME: extra data bytes copied, should use GetDataSize()
    pub fn get_data_size(&self) -> usize {
        let mut size = 0;
        unsafe {
            ll::rocks_writebatch_data(self.raw, &mut size);
        }
        size as usize
    }

    /// Returns the number of updates in the batch
    pub fn count(&self) -> usize {
        unsafe { ll::rocks_writebatch_count(self.raw) as usize }
    }

    /// Returns true if PutCF will be called during Iterate
    pub fn has_put(&self) -> bool {
        unsafe { ll::rocks_writebatch_has_put(self.raw) != 0 }
    }

    /// Returns true if DeleteCF will be called during Iterate
    pub fn has_delete(&self) -> bool {
        unsafe { ll::rocks_writebatch_has_delete(self.raw) != 0 }
    }

    /// Returns true if SingleDeleteCF will be called during Iterate
    pub fn has_single_delete(&self) -> bool {
        unsafe { ll::rocks_writebatch_has_single_delete(self.raw) != 0 }
    }

    /// Returns true if DeleteRangeCF will be called during Iterate
    pub fn has_delete_range(&self) -> bool {
        unsafe { ll::rocks_writebatch_has_delete_range(self.raw) != 0 }
    }

    /// Returns true if MergeCF will be called during Iterate
    pub fn has_merge(&self) -> bool {
        unsafe { ll::rocks_writebatch_has_merge(self.raw) != 0 }
    }

    /// Returns true if MarkBeginPrepare will be called during Iterate
    pub fn has_begin_prepare(&self) -> bool {
        unsafe { ll::rocks_writebatch_has_begin_prepare(self.raw) != 0 }
    }

    /// Returns true if MarkEndPrepare will be called during Iterate
    pub fn has_end_prepare(&self) -> bool {
        unsafe { ll::rocks_writebatch_has_end_prepare(self.raw) != 0 }
    }

    /// Returns trie if MarkCommit will be called during Iterate
    pub fn has_commit(&self) -> bool {
        unsafe { ll::rocks_writebatch_has_commit(self.raw) != 0 }
    }

    /// Returns trie if MarkRollback will be called during Iterate
    pub fn has_rollback(&self) -> bool {
        unsafe { ll::rocks_writebatch_has_put(self.raw) != 0 }
    }
}

/// Support for iterating over the contents of a batch.
///
/// All handler functions in this class provide default implementations so
/// we won't break existing clients of Handler on a source code level when
/// adding a new member function.
pub trait WriteBatchHandler {
    fn put_cf(&mut self, column_family_id: u32, key: &[u8], value: &[u8]) {}
    fn delete_cf(&mut self, column_family_id: u32, key: &[u8]) {}
    fn single_delete_cf(&mut self, column_family_id: u32, key: &[u8]) {}
    fn delete_range_cf(&mut self, column_family_id: u32, begin_key: &[u8], end_key: &[u8]) {}
    fn merge_cf(&mut self, column_family_id: u32, key: &[u8], value: &[u8]) {}
    fn log_data(&mut self, blob: &[u8]) {}
    fn mark_begin_prepare(&mut self) {}
    fn mark_end_prepare(&mut self, xid: &[u8]) {}
    fn mark_rollback(&mut self, xid: &[u8]) {}
    fn mark_commit(&mut self, xid: &[u8]) {}
    /// Continue is called by WriteBatch::Iterate. If it returns false,
    /// iteration is halted. Otherwise, it continues iterating. The default
    /// implementation always returns true.
    fn will_continue(&mut self) -> bool {
        true
    }
}

/// Rust style `WriteBatch` decompose
#[derive(Debug, PartialEq, Eq, Hash)]
pub enum WriteBatchEntry {
    Put {
        column_family_id: u32,
        key: Vec<u8>,
        value: Vec<u8>,
    },
    Delete {
        column_family_id: u32,
        key: Vec<u8>,
    },
    SingleDelete {
        column_family_id: u32,
        key: Vec<u8>,
    },
    DeleteRange {
        column_family_id: u32,
        begin_key: Vec<u8>,
        end_key: Vec<u8>,
    },
    Merge {
        column_family_id: u32,
        key: Vec<u8>,
        value: Vec<u8>,
    },
    LogData {
        blob: Vec<u8>,
    },
    BeginPrepareMark,
    EndPrepareMark {
        xid: Vec<u8>,
    },
    RollbackMark {
        xid: Vec<u8>,
    },
    CommitMark {
        xid: Vec<u8>,
    },
}

#[derive(Default, Debug)]
pub struct WriteBatchIteratorHandler {
    pub entries: Vec<WriteBatchEntry>,
}

impl WriteBatchHandler for WriteBatchIteratorHandler {
    fn put_cf(&mut self, column_family_id: u32, key: &[u8], value: &[u8]) {
        self.entries.push(WriteBatchEntry::Put {
            column_family_id,
            key: key.to_owned(),
            value: value.to_owned(),
        });
    }
    fn delete_cf(&mut self, column_family_id: u32, key: &[u8]) {
        self.entries.push(WriteBatchEntry::Delete {
            column_family_id,
            key: key.to_owned(),
        });
    }
    fn single_delete_cf(&mut self, column_family_id: u32, key: &[u8]) {
        self.entries.push(WriteBatchEntry::SingleDelete {
            column_family_id,
            key: key.to_owned(),
        });
    }
    fn delete_range_cf(&mut self, column_family_id: u32, begin_key: &[u8], end_key: &[u8]) {
        self.entries.push(WriteBatchEntry::DeleteRange {
            column_family_id,
            begin_key: begin_key.to_owned(),
            end_key: end_key.to_owned(),
        });
    }
    fn merge_cf(&mut self, column_family_id: u32, key: &[u8], value: &[u8]) {
        self.entries.push(WriteBatchEntry::Merge {
            column_family_id,
            key: key.to_owned(),
            value: value.to_owned(),
        });
    }
    fn log_data(&mut self, blob: &[u8]) {
        self.entries.push(WriteBatchEntry::LogData { blob: blob.to_owned() });
    }
    fn mark_begin_prepare(&mut self) {
        self.entries.push(WriteBatchEntry::BeginPrepareMark);
    }
    fn mark_end_prepare(&mut self, xid: &[u8]) {
        self.entries
            .push(WriteBatchEntry::EndPrepareMark { xid: xid.to_owned() });
    }
    fn mark_rollback(&mut self, xid: &[u8]) {
        self.entries.push(WriteBatchEntry::RollbackMark { xid: xid.to_owned() });
    }
    fn mark_commit(&mut self, xid: &[u8]) {
        self.entries.push(WriteBatchEntry::CommitMark { xid: xid.to_owned() });
    }
}

// call rust fn in C
#[doc(hidden)]
pub mod c {
    use super::*;

    #[no_mangle]
    pub unsafe extern "C" fn rust_write_batch_handler_put_cf(
        h: *mut (),
        column_family_id: u32,
        key: &&[u8],
        value: &&[u8],
    ) {
        assert!(!h.is_null());
        let handler = h as *mut &mut dyn WriteBatchHandler;
        (*handler).put_cf(column_family_id, key, value);
    }

    #[no_mangle]
    pub unsafe extern "C" fn rust_write_batch_handler_delete_cf(h: *mut (), column_family_id: u32, key: &&[u8]) {
        assert!(!h.is_null());
        let handler = h as *mut &mut dyn WriteBatchHandler;
        (*handler).delete_cf(column_family_id, key);
    }

    #[no_mangle]
    pub unsafe extern "C" fn rust_write_batch_handler_single_delete_cf(h: *mut (), column_family_id: u32, key: &&[u8]) {
        assert!(!h.is_null());
        let handler = h as *mut &mut dyn WriteBatchHandler;
        (*handler).single_delete_cf(column_family_id, key);
    }

    #[no_mangle]
    pub unsafe extern "C" fn rust_write_batch_handler_delete_range_cf(
        h: *mut (),
        column_family_id: u32,
        begin_key: &&[u8],
        end_key: &&[u8],
    ) {
        assert!(!h.is_null());
        let handler = h as *mut &mut dyn WriteBatchHandler;
        (*handler).delete_range_cf(column_family_id, begin_key, end_key);
    }

    #[no_mangle]
    pub unsafe extern "C" fn rust_write_batch_handler_merge_cf(
        h: *mut (),
        column_family_id: u32,
        key: &&[u8],
        value: &&[u8],
    ) {
        assert!(!h.is_null());
        let handler = h as *mut &mut dyn WriteBatchHandler;
        (*handler).merge_cf(column_family_id, key, value);
    }

    #[no_mangle]
    pub unsafe extern "C" fn rust_write_batch_handler_log_data(h: *mut (), blob: &&[u8]) {
        assert!(!h.is_null());
        let handler = h as *mut &mut dyn WriteBatchHandler;
        (*handler).log_data(blob);
    }

    #[no_mangle]
    pub unsafe extern "C" fn rust_write_batch_handler_mark_begin_prepare(h: *mut ()) {
        assert!(!h.is_null());
        let handler = h as *mut &mut dyn WriteBatchHandler;
        (*handler).mark_begin_prepare();
    }

    #[no_mangle]
    pub unsafe extern "C" fn rust_write_batch_handler_mark_end_prepare(h: *mut (), xid: &&[u8]) {
        assert!(!h.is_null());
        let handler = h as *mut &mut dyn WriteBatchHandler;
        (*handler).mark_end_prepare(xid);
    }

    #[no_mangle]
    pub unsafe extern "C" fn rust_write_batch_handler_mark_rollback(h: *mut (), xid: &&[u8]) {
        assert!(!h.is_null());
        let handler = h as *mut &mut dyn WriteBatchHandler;
        (*handler).mark_rollback(xid);
    }

    #[no_mangle]
    pub unsafe extern "C" fn rust_write_batch_handler_mark_commit(h: *mut (), xid: &&[u8]) {
        assert!(!h.is_null());
        let handler = h as *mut &mut dyn WriteBatchHandler;
        (*handler).mark_commit(xid);
    }

    #[no_mangle]
    pub unsafe extern "C" fn rust_write_batch_handler_will_continue(h: *mut ()) -> c_uchar {
        assert!(!h.is_null());
        let handler = h as *mut &mut dyn WriteBatchHandler;
        (*handler).will_continue() as c_uchar
    }

    #[no_mangle]
    pub unsafe extern "C" fn rust_write_batch_handler_drop(h: *mut ()) {
        assert!(!h.is_null());
        let handler = h as *mut &mut dyn WriteBatchHandler;
        Box::from_raw(handler);
    }
}

#[cfg(test)]
mod tests {
    use super::super::rocksdb::*;
    use super::*;

    #[test]
    fn write_batch_create() {
        let mut batch = WriteBatch::new();
        assert!(batch.count() == 0);
        batch.put(b"name", b"rocksdb");
        assert!(batch.count() == 1);
        batch.delete(b"name");
        assert_eq!(batch.count(), 2);

        assert!(batch.has_put());
        assert!(batch.has_delete());
        assert!(!batch.has_commit());
        batch.put_log_data(b"Hello World!");

        let mut handler = WriteBatchIteratorHandler::default();
        let ret = batch.iterate(&mut handler);
        assert!(ret.is_ok(), "error: {:?}", ret);
        assert_eq!(handler.entries.len(), 3);
    }

    #[test]
    fn write_batch() {
        let tmp_dir = ::tempdir::TempDir::new_in(".", "rocks").unwrap();

        let opt = Options::default().map_db_options(|db| db.create_if_missing(true));

        let db = DB::open(opt, &tmp_dir).unwrap();

        let mut batch = WriteBatch::new();
        batch
            .put(b"name", b"BY1CQ")
            .delete(b"name")
            .put(b"name", b"BH1XUW")
            .put(b"site", b"github");

        assert!(db.write(&WriteOptions::default(), &batch).is_ok());

        assert_eq!(db.get(&ReadOptions::default(), b"name").unwrap().as_ref(), b"BH1XUW");
        assert_eq!(db.get(&ReadOptions::default(), b"site").unwrap().as_ref(), b"github");
    }
}