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
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]

extern crate rand;
extern crate siphasher;

use rand::Rand;
use std::borrow::Borrow;
use std::cmp::max;
use std::hash::{Hash, Hasher};

use siphasher::sip::SipHasher13;
type FastHasher = SipHasher13;

use std::marker::PhantomData;
use std::mem;

macro_rules! cms_define {
    ($CountMinSketch:ident, $Counter:ty) => (

pub struct $CountMinSketch<K> {
    counters: Vec<Vec<$Counter>>,
    offsets: Vec<usize>,
    hashers: [FastHasher; 2],
    mask: usize,
    k_num: usize,
    reset_idx: usize,
    phantom_k: PhantomData<K>,
}

impl<K> $CountMinSketch<K>
    where K: Hash
{
    pub fn new(capacity: usize, probability: f64, tolerance: f64) -> Result<Self, &'static str> {
        let width = Self::optimal_width(capacity, tolerance);
        let k_num = Self::optimal_k_num(probability);
        let counters: Vec<Vec<$Counter>> = vec![vec![0; width]; k_num];
        let offsets = vec![0; k_num];
        let hashers = [Self::sip_new(), Self::sip_new()];
        let cms = $CountMinSketch {
            counters: counters,
            offsets: offsets,
            hashers: hashers,
            mask: Self::mask(width),
            k_num: k_num,
            reset_idx: 0,
            phantom_k: PhantomData,
        };
        Ok(cms)
    }

    pub fn add<Q: ?Sized>(&mut self, key: &Q, value: $Counter) where Q: Hash, K: Borrow<Q> {
        let mut hashes = [0u64, 0u64];
        let lowest = (0..self.k_num)
            .map(|k_i| {
                let offset = self.offset(&mut hashes, key, k_i);
                self.offsets[k_i] = offset;
                self.counters[k_i][offset]
            })
            .min()
            .unwrap();
        for k_i in 0..self.k_num {
            let offset = self.offsets[k_i];
            if self.counters[k_i][offset] == lowest {
                self.counters[k_i][offset] = self.counters[k_i][offset].saturating_add(value);
            }
        }
    }

    pub fn increment<Q: ?Sized>(&mut self, key: &Q) where Q: Hash, K: Borrow<Q> {
        self.add(key, 1)
    }

    pub fn estimate<Q: ?Sized>(&self, key: &Q) -> $Counter where Q: Hash, K: Borrow<Q> {
        let mut hashes = [0u64, 0u64];
        (0..self.k_num)
            .map(|k_i| {
                let offset = self.offset(&mut hashes, key, k_i);
                self.counters[k_i][offset]
            })
            .min()
            .unwrap()
    }

    pub fn estimate_memory(capacity: usize,
                           probability: f64,
                           tolerance: f64)
                           -> Result<usize, &'static str> {
        let width = Self::optimal_width(capacity, tolerance);
        let k_num = Self::optimal_k_num(probability);
        Ok(width * mem::size_of::<$Counter>() * k_num)
    }

    pub fn clear(&mut self) {
        for k_i in 0..self.k_num {
            for counter in &mut self.counters[k_i] {
                *counter = 0
            }
        }
        self.reset_idx = 0;
        self.hashers = [Self::sip_new(), Self::sip_new()];
    }

    pub fn reset(&mut self) {
        for k_i in 0..self.k_num {
            for counter in &mut self.counters[k_i] {
                *counter /= 2;
            }
        }
        self.reset_idx = 0;
    }

    pub fn reset_next(&mut self) -> Option<usize> {
        let idx = self.reset_idx;
        for k_i in 0..self.k_num {
            self.counters[k_i][idx] /= 2
        }
        let next = idx.wrapping_add(1) & self.mask;
        self.reset_idx = next;
        if next != 0 { Some(next) } else { None }
    }

    fn optimal_width(capacity: usize, tolerance: f64) -> usize {
        let e = tolerance / (capacity as f64);
        let width = (2.0 / e).round() as usize;
        max(2, width).checked_next_power_of_two().expect("Width would be way too large")
    }

    fn mask(width: usize) -> usize {
        assert!(width > 1);
        assert!(width & (width - 1) == 0);
        width - 1
    }

    fn optimal_k_num(probability: f64) -> usize {
        max(1, ((1.0 - probability).ln() / 0.5f64.ln()) as usize)
    }

    fn sip_new() -> FastHasher {
        let mut rng = rand::thread_rng();
        FastHasher::new_with_keys(Rand::rand(&mut rng), Rand::rand(&mut rng))
    }

    fn offset<Q: ?Sized>(&self, hashes: &mut [u64; 2], key: &Q, k_i: usize)
    -> usize where Q: Hash, K: Borrow<Q> {
        if k_i < 2 {
            let sip = &mut self.hashers[k_i as usize].clone();
            key.hash(sip);
            let hash = sip.finish();
            hashes[k_i as usize] = hash;
            hash as usize & self.mask
        } else {
            hashes[0]
                .wrapping_add((k_i as u64).wrapping_mul(hashes[1]) %
                              0xffffffffffffffc5) as usize & self.mask
        }
    }
}

)} // macro_rules! cms_define

cms_define!(CountMinSketch8, u8);
cms_define!(CountMinSketch16, u16);
cms_define!(CountMinSketch32, u32);
cms_define!(CountMinSketch64, u64);

#[cfg(test)]
mod tests {
    #[test]
    fn test_overflow() {
        use CountMinSketch8;

        let mut cms = CountMinSketch8::<&str>::new(100, 0.95, 10.0).unwrap();
        for _ in 0..300 {
            cms.increment("key");
        }
        assert!(cms.estimate("key") == u8::max_value());
    }

    #[test]
    fn test_increment() {
        use CountMinSketch16;

        let mut cms = CountMinSketch16::<&str>::new(100, 0.95, 10.0).unwrap();
        for _ in 0..300 {
            cms.increment("key");
        }
        assert!(cms.estimate("key") == 300);
    }

    #[test]
    fn test_increment_multi() {
        use CountMinSketch64;

        let mut cms = CountMinSketch64::<u64>::new(100, 0.99, 2.0).unwrap();
        for i in 0..1_000_000 {
            cms.increment(&(i % 100));
        }
        for key in 0..100 {
            assert!(cms.estimate(&key) >= 9_000);
        }
        cms.reset();
        for key in 0..100 {
            assert!(cms.estimate(&key) < 11_000);
        }
    }
}