From 426fa60f7113735a0243abd8185c4eeb6c547c38 Mon Sep 17 00:00:00 2001 From: josh Date: Fri, 4 Sep 2020 13:02:39 -0700 Subject: [PATCH] Add parameterizable Init funciton --- ring.go | 20 ++++++++++++++++++++ ring_test.go | 8 ++++++++ 2 files changed, 28 insertions(+) diff --git a/ring.go b/ring.go index 0951e8e..0647eb4 100644 --- a/ring.go +++ b/ring.go @@ -15,6 +15,7 @@ import ( var ( errElements = errors.New("error: elements must be greater than 0") errFalsePositive = errors.New("error: falsePositive must be greater than 0 and less than 1") + errHash = errors.New("error: Hash functions must be greater than zero") ) // Ring contains the information for a ring data store. @@ -49,6 +50,25 @@ func Init(elements int, falsePositive float64) (*Ring, error) { return &r, nil } +// InitByParameters initializes a bloom filter allowing the user to explicitly set +// the size of the bit array and the amount of hash functions +func InitByParameters(size, hashFunctions uint64) (*Ring, error) { + if size <= 0 { + return nil, errElements + } + if hashFunctions <= 0 { + return nil, errHash + } + + r := Ring{} + + r.mutex = &sync.RWMutex{} + r.size = size + r.hash = hashFunctions + r.bits = make([]uint8, r.size/8+1) + return &r, nil +} + // Add adds the data to the ring. func (r *Ring) Add(data []byte) { // generate hashes diff --git a/ring_test.go b/ring_test.go index fcab063..045f33a 100644 --- a/ring_test.go +++ b/ring_test.go @@ -106,6 +106,14 @@ func TestBadParameters(t *testing.T) { if err == nil { t.Fatal("element <= 0 not captured") } + + // InitByParameters tests + + _, err = ring.InitByParameters(1, 0) + if err != nil { + t.Fatal("Hash function cannot be <=0") + } + } // TestReset ensures the Ring is cleared on Reset().