-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathredis.rb
76 lines (61 loc) · 1.74 KB
/
redis.rb
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
73
74
75
76
module BloomFilter
class Redis < Filter
def initialize(opts = {})
@opts = {
:size => 100,
:hashes => 4,
:seed => Time.now.to_i,
:namespace => 'redis',
:eager => false,
:server => {}
}.merge opts
@db = @opts.delete(:db) || ::Redis.new(@opts[:server])
if @opts[:eager]
@db.setbit @opts[:namespace], @opts[:size]+1, 1
end
end
def insert(key, ttl=nil)
@db.pipelined do |db|
indexes_for(key) { |idx| db.setbit @opts[:namespace], idx, 1 }
end
end
alias :[]= :insert
def include?(*keys)
keys.each do |key|
indexes = []
indexes_for(key) { |idx| indexes << idx }
return false if @db.getbit(@opts[:namespace], indexes.shift) == 0
result = @db.pipelined do |db|
indexes.each do |idx|
db.getbit(@opts[:namespace], idx)
end
end
return false if result.include?(0)
end
true
end
alias :key? :include?
def delete(key)
warn "Deletes are disabled on non-counting filter, see: https://github.com/igrigorik/bloomfilter-rb/issues/37. This method will be deprecated in a future release."
end
def clear
@db.set @opts[:namespace], 0
end
def num_set
@db.strlen @opts[:namespace]
end
alias :size :num_set
def stats
printf "Number of filter buckets (m): %d\n" % @opts[:size]
printf "Number of filter hashes (k) : %d\n" % @opts[:hashes]
end
private
# compute index offsets for provided key
def indexes_for(key)
indexes = []
@opts[:hashes].times do |i|
yield Zlib.crc32("#{key}:#{i+@opts[:seed]}") % @opts[:size]
end
end
end
end