github.com/panmari/cuckoofilter@v1.0.7-0.20231223155748-763d1d471ee8/bucket.go (about) 1 package cuckoo 2 3 import ( 4 "bytes" 5 "fmt" 6 ) 7 8 // fingerprint represents a single entry in a bucket. 9 type fingerprint uint16 10 11 // bucket keeps track of fingerprints hashing to the same index. 12 type bucket [bucketSize]fingerprint 13 14 const ( 15 nullFp = 0 16 bucketSize = 4 17 fingerprintSizeBits = 16 18 maxFingerprint = (1 << fingerprintSizeBits) - 1 19 ) 20 21 // insert a fingerprint into a bucket. Returns true if there was enough space and insertion succeeded. 22 // Note it allows inserting the same fingerprint multiple times. 23 func (b *bucket) insert(fp fingerprint) bool { 24 for i, tfp := range b { 25 if tfp == nullFp { 26 b[i] = fp 27 return true 28 } 29 } 30 return false 31 } 32 33 // delete a fingerprint from a bucket. 34 // Returns true if the fingerprint was present and successfully removed. 35 func (b *bucket) delete(fp fingerprint) bool { 36 for i, tfp := range b { 37 if tfp == fp { 38 b[i] = nullFp 39 return true 40 } 41 } 42 return false 43 } 44 45 func (b *bucket) contains(needle fingerprint) bool { 46 for _, fp := range b { 47 if fp == needle { 48 return true 49 } 50 } 51 return false 52 } 53 54 // reset deletes all fingerprints in the bucket. 55 func (b *bucket) reset() { 56 for i := range b { 57 b[i] = nullFp 58 } 59 } 60 61 func (b *bucket) String() string { 62 var buf bytes.Buffer 63 buf.WriteString("[") 64 for _, by := range b { 65 buf.WriteString(fmt.Sprintf("%5d ", by)) 66 } 67 buf.WriteString("]") 68 return buf.String() 69 }