github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/database/leveldb.chai2010/filter_policy.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 // Filter is the filter. 12 type Filter interface { 13 // Return the name of this policy. Note that if the filter encoding 14 // changes in an incompatible way, the name returned by this method 15 // must be changed. Otherwise, old incompatible filters may be 16 // passed to methods of this type. 17 Name() string 18 19 // keys[0,n-1] contains a list of keys (potentially with duplicates) 20 // that are ordered according to the user supplied comparator. 21 // Append a filter that summarizes keys[0,n-1] to *dst. 22 // 23 // Warning: do not change the initial contents of *dst. Instead, 24 // append the newly constructed filter to *dst. 25 CreateFilter(keys [][]byte) []byte 26 27 // "filter" contains the data appended by a preceding call to 28 // CreateFilter() on this class. This method must return true if 29 // the key was in the list of keys passed to CreateFilter(). 30 // This method may return true or false if the key was not on the 31 // list, but it should aim to return false with a high probability. 32 KeyMayMatch(key, filter []byte) bool 33 } 34 35 type BloomFilter struct { 36 *bloomFilterHandler 37 } 38 type bloomFilterHandler struct { 39 filter *leveldb_filterpolicy_t 40 } 41 42 func newBloomFilter(bitsPerKey int) *BloomFilter { 43 p := &bloomFilterHandler{ 44 filter: leveldb_filterpolicy_create_bloom(bitsPerKey), 45 } 46 runtime.SetFinalizer(p, (*bloomFilterHandler).Release) 47 return &BloomFilter{p} 48 } 49 50 func (p *bloomFilterHandler) Release() { 51 runtime.SetFinalizer(p, nil) 52 leveldb_filterpolicy_destroy(p.filter) 53 *p = bloomFilterHandler{} 54 } 55 56 func (p *bloomFilterHandler) Name() string { 57 return leveldb_filterpolicy_name(p.filter) 58 } 59 60 func (p *bloomFilterHandler) CreateFilter(keys [][]byte) []byte { 61 d := leveldb_filterpolicy_create_filter(p.filter, keys) 62 defer leveldb_value_destroy(d) 63 return append([]byte{}, leveldb_value_data(d)...) 64 } 65 66 func (p *bloomFilterHandler) KeyMayMatch(key, filter []byte) bool { 67 return leveldb_filterpolicy_key_may_match(p.filter, key, filter) 68 } 69 70 // NewBloomFilter creates a new initialized bloom filter for given 71 // bitsPerKey. 72 // 73 // Since bitsPerKey is persisted individually for each bloom filter 74 // serialization, bloom filters are backwards compatible with respect to 75 // changing bitsPerKey. This means that no big performance penalty will 76 // be experienced when changing the parameter. See documentation for 77 // opt.Options.Filter for more information. 78 func NewBloomFilterPolicy(bitsPerKey int) *BloomFilter { 79 return newBloomFilter(bitsPerKey) 80 }