diff --git a/src/leveldb.nim b/src/leveldb.nim index 6ba9275..b51a657 100644 --- a/src/leveldb.nim +++ b/src/leveldb.nim @@ -6,6 +6,7 @@ type syncWriteOptions: ptr leveldb_writeoptions_t asyncWriteOptions: ptr leveldb_writeoptions_t readOptions: ptr leveldb_readoptions_t + cache: ptr leveldb_cache_t LevelDbBatch* = ref object batch: ptr leveldb_writebatch_t @@ -36,9 +37,12 @@ proc close*(self: LevelDb) = leveldb_writeoptions_destroy(self.syncWriteOptions) leveldb_writeoptions_destroy(self.asyncWriteOptions) leveldb_readoptions_destroy(self.readOptions) + if self.cache != nil: + leveldb_cache_destroy(self.cache) + self.cache = nil self.db = nil -proc open*(path: string): LevelDb = +proc open*(path: string, cacheCapacity = 0): LevelDb = new(result, close) let options = leveldb_options_create() @@ -51,6 +55,11 @@ proc open*(path: string): LevelDb = leveldb_writeoptions_set_sync(result.asyncWriteOptions, levelDbFalse) result.readOptions = leveldb_readoptions_create() + if cacheCapacity > 0: + let cache = leveldb_cache_create_lru(cacheCapacity) + leveldb_options_set_cache(options, cache) + result.cache = cache + var errPtr: cstring = nil result.db = leveldb_open(options, path, addr errPtr) checkError(errPtr) diff --git a/tests/test.nim b/tests/test.nim index 4e63032..c1d79c6 100644 --- a/tests/test.nim +++ b/tests/test.nim @@ -104,3 +104,8 @@ suite "leveldb": batch.put("b", "2") db.write(batch) check(toSeq(db.iter()) == @[("b", "2")]) + + test "open with cache": + let ldb = leveldb.open(dbName & "-cache", cacheCapacity = 100000) + ldb.put("a", "1") + check(toSeq(ldb.iter()) == @[("a", "1")])