1 /** 2 * D-LevelDB Write Batch 3 * 4 * WriteBatch holds multiple writes that can be applied to an open DB in a sinlge 5 * atomic update. 6 * 7 * Copyright: Copyright © 2013 Byron Heads 8 * License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>. 9 * Authors: Byron Heads 10 */ 11 /* Copyright © 2013 Byron Heads 12 * Distributed under the Boost Software License, Version 1.0. 13 * (See accompanying file LICENSE_1_0.txt or copy at 14 * http://www.boost.org/LICENSE_1_0.txt) 15 */ 16 module leveldb.writebatch; 17 /+ 18 19 private import leveldb.exceptions, 20 leveldb.slice; 21 private import deimos.leveldb.leveldb; 22 23 class WriteBatch 24 { 25 private: 26 leveldb_writebatch_t _ptr; 27 28 package: 29 @property 30 inout(leveldb_writebatch_t) ptr() inout 31 { 32 return _ptr; 33 } 34 35 public: 36 this() 37 { 38 if((_ptr = leveldb_writebatch_create()) is null) 39 throw new LeveldbException("Failed to create batch writer"); 40 } 41 42 ~this() 43 { 44 if(valid) 45 { 46 leveldb_writebatch_destroy(_ptr); 47 _ptr = null; 48 } 49 } 50 51 @property 52 void clear() 53 { 54 leveldb_writebatch_clear(_ptr); 55 } 56 57 void put(K, V)(K key, V val) 58 { 59 put_raw(key._lib_obj_ptr__, key._lib_obj_size__, val._lib_obj_ptr__, val._lib_obj_size__); 60 } 61 62 private 63 void put_raw(const(char*) key, size_t keylen, const(char*)val, size_t vallen) 64 { 65 leveldb_writebatch_put(_ptr, key, keylen, val, vallen); 66 } 67 68 void del(T)(T key) 69 { 70 leveldb_writebatch_delete(_ptr, key._lib_obj_ptr__, key._lib_obj_size__); 71 } 72 73 void iterate(Visitor visitor) 74 { 75 leveldb_writebatch_iterate(_ptr, cast(void*)&visitor, 76 &batchPut, &batchDel); 77 } 78 79 void iterate(void delegate(Slice key, Slice value) puts, 80 void delegate(Slice key) dels) 81 { 82 iterate(Visitor(puts, dels)); 83 } 84 85 @property 86 bool valid() inout 87 { 88 return _ptr !is null; 89 } 90 91 static struct Visitor 92 { 93 void delegate(Slice key, Slice value) puts; 94 void delegate(Slice key) dels; 95 } 96 } // WriteBatch 97 98 99 private: 100 extern(C): 101 102 void batchPut(void* state, const char* k, size_t klen, const char* v, size_t vlen) 103 { 104 auto visitor = cast(WriteBatch.Visitor*)state; 105 visitor.puts(Slice(cast(void*)k, klen, true), Slice(cast(void*)v, vlen, true)); 106 } 107 108 void batchDel(void* state, const char* k, size_t klen) 109 { 110 auto visitor = cast(WriteBatch.Visitor*)state; 111 visitor.dels(Slice(cast(void*)k, klen, true)); 112 } 113 +/