github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/database/leveldb/batch.go (about)

     1  // Copyright 2013 <chaishushan{AT}gmail.com>. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package leveldb
     6  
     7  // #include <leveldb/c.h>
     8  import "C"
     9  import "unsafe"
    10  
    11  // WriteBatch is a batching of Puts, and Deletes to be written atomically to a
    12  // database. A WriteBatch is written when passed to DB.Write.
    13  //
    14  // To prevent memory leaks, call Close when the program no longer needs the
    15  // WriteBatch object.
    16  type WriteBatch struct {
    17  	wbatch *C.leveldb_writebatch_t
    18  }
    19  
    20  // NewWriteBatch creates a fully allocated WriteBatch.
    21  func NewWriteBatch() *WriteBatch {
    22  	wb := C.leveldb_writebatch_create()
    23  	return &WriteBatch{wb}
    24  }
    25  
    26  // Close releases the underlying memory of a WriteBatch.
    27  func (w *WriteBatch) Close() {
    28  	C.leveldb_writebatch_destroy(w.wbatch)
    29  }
    30  
    31  // Put places a key-value pair into the WriteBatch for writing later.
    32  //
    33  // Both the key and value byte slices may be reused as WriteBatch takes a copy
    34  // of them before returning.
    35  //
    36  func (w *WriteBatch) Put(key, value []byte) {
    37  	// leveldb_writebatch_put, and _delete call memcpy() (by way of
    38  	// Memtable::Add) when called, so we do not need to worry about these
    39  	// []byte being reclaimed by GC.
    40  	var k, v *C.char
    41  	if len(key) != 0 {
    42  		k = (*C.char)(unsafe.Pointer(&key[0]))
    43  	}
    44  	if len(value) != 0 {
    45  		v = (*C.char)(unsafe.Pointer(&value[0]))
    46  	}
    47  	C.leveldb_writebatch_put(w.wbatch,
    48  		k, C.size_t(len(key)),
    49  		v, C.size_t(len(value)),
    50  	)
    51  }
    52  
    53  // Delete queues a deletion of the data at key to be deleted later.
    54  //
    55  // The key byte slice may be reused safely. Delete takes a copy of
    56  // them before returning.
    57  func (w *WriteBatch) Delete(key []byte) {
    58  	C.leveldb_writebatch_delete(w.wbatch,
    59  		(*C.char)(unsafe.Pointer(&key[0])), C.size_t(len(key)),
    60  	)
    61  }
    62  
    63  // Clear removes all the enqueued Put and Deletes in the WriteBatch.
    64  func (w *WriteBatch) Clear() {
    65  	C.leveldb_writebatch_clear(w.wbatch)
    66  }