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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// This file includes source code from https://github.com/jedisct1/rust-count-min-sketch/blob/088274e22a3decc986dec928c92cc90a709a0274/src/lib.rs under the following MIT License:

// Copyright (c) 2016 Frank Denis

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use serde::{Deserialize, Serialize};
use std::{
	borrow::Borrow, cmp::max, convert::TryFrom, fmt, hash::{Hash, Hasher}, marker::PhantomData, ops
};
use twox_hash::XxHash;

use super::f64_to_usize;
use crate::traits::{Intersect, IntersectPlusUnionIsPlus, New, UnionAssign};

/// An implementation of a [count-min sketch](https://en.wikipedia.org/wiki/Count–min_sketch) data structure with *conservative updating* for increased accuracy.
///
/// This data structure is also known as a [counting Bloom filter](https://en.wikipedia.org/wiki/Bloom_filter#Counting_filters).
///
/// See [*An Improved Data Stream Summary: The Count-Min Sketch and its Applications*](http://dimacs.rutgers.edu/~graham/pubs/papers/cm-full.pdf) and [*New Directions in Traffic Measurement and Accounting*](http://pages.cs.wisc.edu/~suman/courses/740/papers/estan03tocs.pdf) for background on the count-min sketch with conservative updating.
#[derive(Serialize, Deserialize)]
#[serde(bound(
	serialize = "C: Serialize, <C as New>::Config: Serialize",
	deserialize = "C: Deserialize<'de>, <C as New>::Config: Deserialize<'de>"
))]
pub struct CountMinSketch<K: ?Sized, C: New> {
	counters: Vec<Vec<C>>,
	offsets: Vec<usize>, // to avoid malloc/free each push
	mask: usize,
	k_num: usize,
	config: <C as New>::Config,
	marker: PhantomData<fn(K)>,
}

impl<K: ?Sized, C> CountMinSketch<K, C>
where
	K: Hash,
	C: New + for<'a> UnionAssign<&'a C> + Intersect,
{
	/// Create an empty `CountMinSketch` data structure with the specified error tolerance.
	pub fn new(probability: f64, tolerance: f64, config: C::Config) -> Self {
		let width = Self::optimal_width(tolerance);
		let k_num = Self::optimal_k_num(probability);
		let counters: Vec<Vec<C>> = (0..k_num)
			.map(|_| (0..width).map(|_| C::new(&config)).collect())
			.collect();
		let offsets = vec![0; k_num];
		Self {
			counters,
			offsets,
			mask: Self::mask(width),
			k_num,
			config,
			marker: PhantomData,
		}
	}

	/// "Visit" an element.
	pub fn push<Q: ?Sized, V: ?Sized>(&mut self, key: &Q, value: &V) -> C
	where
		Q: Hash,
		K: Borrow<Q>,
		C: for<'a> ops::AddAssign<&'a V> + IntersectPlusUnionIsPlus,
	{
		let offsets = self.offsets(key);
		if !<C as IntersectPlusUnionIsPlus>::VAL {
			self.offsets
				.iter_mut()
				.zip(offsets)
				.for_each(|(offset, offset_new)| {
					*offset = offset_new;
				});
			let mut lowest = C::intersect(
				self.offsets
					.iter()
					.enumerate()
					.map(|(k_i, &offset)| &self.counters[k_i][offset]),
			)
			.unwrap();
			lowest += value;
			self.counters
				.iter_mut()
				.zip(self.offsets.iter())
				.for_each(|(counters, &offset)| {
					counters[offset].union_assign(&lowest);
				});
			lowest
		} else {
			C::intersect(
				self.counters
					.iter_mut()
					.zip(offsets)
					.map(|(counters, offset)| {
						counters[offset] += value;
						&counters[offset]
					}),
			)
			.unwrap()
		}
	}

	/// Union the aggregated value for `key` with `value`.
	pub fn union_assign<Q: ?Sized>(&mut self, key: &Q, value: &C)
	where
		Q: Hash,
		K: Borrow<Q>,
	{
		let offsets = self.offsets(key);
		self.counters
			.iter_mut()
			.zip(offsets)
			.for_each(|(counters, offset)| {
				counters[offset].union_assign(value);
			})
	}

	/// Retrieve an estimate of the aggregated value for `key`.
	pub fn get<Q: ?Sized>(&self, key: &Q) -> C
	where
		Q: Hash,
		K: Borrow<Q>,
	{
		C::intersect(
			self.counters
				.iter()
				.zip(self.offsets(key))
				.map(|(counters, offset)| &counters[offset]),
		)
		.unwrap()
	}

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

	/// Clears the `CountMinSketch` data structure, as if it was new.
	pub fn clear(&mut self) {
		let config = &self.config;
		self.counters
			.iter_mut()
			.flat_map(|x| x.iter_mut())
			.for_each(|counter| {
				*counter = C::new(config);
			})
	}

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

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

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

	fn offsets<Q: ?Sized>(&self, key: &Q) -> impl Iterator<Item = usize>
	where
		Q: Hash,
		K: Borrow<Q>,
	{
		let mask = self.mask;
		hashes(key).map(move |hash| usize::try_from(hash & u64::try_from(mask).unwrap()).unwrap())
	}
}

fn hashes<Q: ?Sized>(key: &Q) -> impl Iterator<Item = u64>
where
	Q: Hash,
{
	#[allow(missing_copy_implementations, missing_debug_implementations)]
	struct X(XxHash);
	impl Iterator for X {
		type Item = u64;
		fn next(&mut self) -> Option<Self::Item> {
			let ret = self.0.finish();
			self.0.write(&[123]);
			Some(ret)
		}
	}
	let mut hasher = XxHash::default();
	key.hash(&mut hasher);
	X(hasher)
}

impl<K: ?Sized, C: New + Clone> Clone for CountMinSketch<K, C> {
	fn clone(&self) -> Self {
		Self {
			counters: self.counters.clone(),
			offsets: vec![0; self.offsets.len()],
			mask: self.mask,
			k_num: self.k_num,
			config: self.config.clone(),
			marker: PhantomData,
		}
	}
}
impl<K: ?Sized, C: New> fmt::Debug for CountMinSketch<K, C> {
	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
		fmt.debug_struct("CountMinSketch")
			// .field("counters", &self.counters)
			.finish()
	}
}

#[cfg(test)]
mod tests {
	type CountMinSketch8<K> = super::CountMinSketch<K, u8>;
	type CountMinSketch16<K> = super::CountMinSketch<K, u16>;
	type CountMinSketch64<K> = super::CountMinSketch<K, u64>;

	#[ignore] // release mode stops panic
	#[test]
	#[should_panic]
	fn test_overflow() {
		let mut cms = CountMinSketch8::<&str>::new(0.95, 10.0 / 100.0, ());
		for _ in 0..300 {
			let _ = cms.push("key", &1);
		}
		// assert_eq!(cms.get("key"), &u8::max_value());
	}

	#[test]
	fn test_increment() {
		let mut cms = CountMinSketch16::<&str>::new(0.95, 10.0 / 100.0, ());
		for _ in 0..300 {
			let _ = cms.push("key", &1);
		}
		assert_eq!(cms.get("key"), 300);
	}

	#[test]
	#[cfg_attr(miri, ignore)]
	fn test_increment_multi() {
		let mut cms = CountMinSketch64::<u64>::new(0.99, 2.0 / 100.0, ());
		for i in 0..1_000_000 {
			let _ = cms.push(&(i % 100), &1);
		}
		for key in 0..100 {
			assert!(cms.get(&key) >= 9_000);
		}
		// cms.reset();
		// for key in 0..100 {
		//     assert!(cms.get(&key) < 11_000);
		// }
	}
}