-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgloom.go
More file actions
72 lines (59 loc) · 1.34 KB
/
gloom.go
File metadata and controls
72 lines (59 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package gloom
import (
"encoding/binary"
"errors"
"fmt"
"io"
"math/big"
"os"
)
const FILTER_SIZE = 32
var (
ErrNotFound = errors.New("nothing found for that key")
)
type Gloom struct {
filter big.Int
hashers []func([]byte) int
}
// Add a hasher
func (g *Gloom) Add(f func([]byte) []byte) {
g.hashers = append(g.hashers, func(b []byte) int {
h := f(b)
n := binary.BigEndian.Uint64(h)
i := n % FILTER_SIZE
return int(i)
})
}
// Put an element by (always) writing to disk and updating the filter
func (g *Gloom) Put(key []byte, value []byte) error {
f, err := os.Create(string(key))
if err != nil {
return fmt.Errorf("error opening file: %w", err)
}
defer f.Close()
if _, err := f.Write(value); err != nil {
return fmt.Errorf("error writing value to disk: %w", err)
}
for _, h := range g.hashers {
g.filter.SetBit(&g.filter, h(key), 1)
}
return nil
}
// Get an element by checking the filter and (maybe) reading from disk
func (g *Gloom) Get(key []byte) ([]byte, error) {
for _, h := range g.hashers {
if g.filter.Bit(h(key)) == 0 {
return nil, ErrNotFound
}
}
f, err := os.Open(string(key))
if err != nil {
return nil, fmt.Errorf("error opening file: %w", err)
}
defer f.Close()
value, err := io.ReadAll(f)
if err != nil {
return nil, fmt.Errorf("error reading value from disk: %w", err)
}
return value, nil
}