github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/database/leveldb.chai2010/cache.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 // Cache is a cache used to store data read from data in memory. 12 type Cache struct { 13 *cacheHandler 14 } 15 type cacheHandler struct { 16 cache *leveldb_cache_t 17 } 18 19 // NewCache creates a new cache with a fixed size capacity. 20 func NewCache(capacity int64) *Cache { 21 p := &cacheHandler{ 22 cache: leveldb_cache_create_lru(capacity), 23 } 24 runtime.SetFinalizer(p, (*cacheHandler).Release) 25 return &Cache{p} 26 } 27 28 // Release releases deallocates the underlying memory of the Cache object. 29 func (p *cacheHandler) Release() { 30 runtime.SetFinalizer(p, nil) 31 leveldb_cache_destroy(p.cache) 32 *p = cacheHandler{} 33 } 34 35 // Insert inserts a mapping from key->value into the cache and assign it 36 // the specified charge against the total cache capacity. 37 func (p *cacheHandler) Insert(key, val []byte) { 38 leveldb_cache_insert(p.cache, key, val) 39 } 40 41 // Lookup get the cached value by key. 42 // If the cache has no mapping for "key", returns nil. 43 func (p *cacheHandler) Lookup(key []byte) *Value { 44 return newValueHandler(leveldb_cache_lookup(p.cache, key)) 45 } 46 47 // Erase erase the cached value by key. 48 func (p *cacheHandler) Erase(key []byte) { 49 leveldb_cache_erase(p.cache, key) 50 }