github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/database/leveldb.chai2010/write_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 import ( 8 "runtime" 9 ) 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 type WriteBatch struct { 14 *writeBatchHandler 15 } 16 type writeBatchHandler struct { 17 batch *leveldb_writebatch_t 18 iterater stateWriteBatchIterater 19 } 20 21 // WriteBatchIterater iterates over a WriteBatch. 22 type WriteBatchIterater interface { 23 Put(key, val []byte) 24 Delete(key []byte) 25 } 26 27 // NewWriteBatch creates a fully allocated WriteBatch. 28 func NewWriteBatch() *WriteBatch { 29 p := &writeBatchHandler{ 30 batch: leveldb_writebatch_create(), 31 } 32 runtime.SetFinalizer(p, (*writeBatchHandler).Release) 33 return &WriteBatch{writeBatchHandler: p} 34 } 35 36 // Release releases the underlying memory of a WriteBatch. 37 func (p *writeBatchHandler) Release() { 38 runtime.SetFinalizer(p, nil) 39 leveldb_writebatch_destroy(p.batch) 40 *p = writeBatchHandler{} 41 } 42 43 // Put places a key-value pair into the WriteBatch for writing later. 44 // 45 // Both the key and value byte slices may be reused as WriteBatch takes a copy 46 // of them before returning. 47 func (p *writeBatchHandler) Put(key, val []byte) { 48 leveldb_writebatch_put(p.batch, key, val) 49 } 50 51 // Delete queues a deletion of the data at key to be deleted later. 52 // 53 // The key byte slice may be reused safely. Delete takes a copy of 54 // them before returning. 55 func (p *writeBatchHandler) Delete(key []byte) { 56 leveldb_writebatch_delete(p.batch, key) 57 } 58 59 // Clear removes all the enqueued Put and Deletes in the WriteBatch. 60 func (p *writeBatchHandler) Clear() { 61 leveldb_writebatch_clear(p.batch) 62 } 63 64 // Iterate iterating over the contents of a batch. 65 func (p *writeBatchHandler) Iterate(handler WriteBatchIterater) { 66 p.iterater.WriteBatchIterater = handler 67 leveldb_writebatch_iterate(p.batch, &p.iterater) 68 }