2013-08-10 12:06:09 +02:00
|
|
|
/**
|
|
|
|
* Bloom filter implementation
|
2013-08-04 22:01:11 +02:00
|
|
|
*
|
2013-08-10 12:06:09 +02:00
|
|
|
* Copyright (C) 2013 Freie Universität Berlin
|
2013-08-04 22:01:11 +02:00
|
|
|
*
|
2014-07-31 19:45:27 +02:00
|
|
|
* This file is subject to the terms and conditions of the GNU Lesser
|
|
|
|
* General Public License v2.1. See the file LICENSE in the top level
|
|
|
|
* directory for more details.
|
2013-08-04 22:01:11 +02:00
|
|
|
*
|
2013-08-10 12:06:09 +02:00
|
|
|
* @file
|
2014-01-24 19:04:28 +01:00
|
|
|
* @author Jason Linehan <patientulysses@gmail.com>
|
|
|
|
* @author Christian Mehlis <mehlis@inf.fu-berlin.de>
|
2013-08-04 22:01:11 +02:00
|
|
|
*
|
2013-08-10 12:06:09 +02:00
|
|
|
*/
|
2013-08-04 22:01:11 +02:00
|
|
|
|
|
|
|
#include <limits.h>
|
|
|
|
#include <stdarg.h>
|
|
|
|
#include <stdbool.h>
|
|
|
|
|
|
|
|
#include "bloom.h"
|
2015-09-01 21:42:33 +02:00
|
|
|
#include "bitfield.h"
|
|
|
|
#include "string.h"
|
2013-08-04 22:01:11 +02:00
|
|
|
|
|
|
|
#define ROUND(size) ((size + CHAR_BIT - 1) / CHAR_BIT)
|
|
|
|
|
2015-09-01 21:42:33 +02:00
|
|
|
void bloom_init(bloom_t *bloom, size_t size, uint8_t *bitfield, hashfp_t *hashes, int hashes_numof)
|
2013-08-20 09:05:07 +02:00
|
|
|
{
|
2013-08-04 22:01:11 +02:00
|
|
|
bloom->m = size;
|
2015-09-01 21:42:33 +02:00
|
|
|
bloom->a = bitfield;
|
|
|
|
bloom->hash = hashes;
|
|
|
|
bloom->k = hashes_numof;
|
2013-08-04 22:01:11 +02:00
|
|
|
}
|
|
|
|
|
2014-09-17 19:54:40 +02:00
|
|
|
void bloom_del(bloom_t *bloom)
|
2013-08-04 22:01:11 +02:00
|
|
|
{
|
2015-09-01 21:42:33 +02:00
|
|
|
if (bloom->a) {
|
|
|
|
memset(bloom->a, 0, ROUND(bloom->m));
|
|
|
|
}
|
|
|
|
bloom->a = NULL;
|
|
|
|
bloom->m = 0;
|
|
|
|
bloom->hash = NULL;
|
|
|
|
bloom->k = 0;
|
2013-08-04 22:01:11 +02:00
|
|
|
}
|
|
|
|
|
2014-09-17 19:54:40 +02:00
|
|
|
void bloom_add(bloom_t *bloom, const uint8_t *buf, size_t len)
|
2013-08-04 22:01:11 +02:00
|
|
|
{
|
2014-08-11 19:51:23 +02:00
|
|
|
for (size_t n = 0; n < bloom->k; n++) {
|
|
|
|
uint32_t hash = bloom->hash[n](buf, len);
|
2015-09-01 21:42:33 +02:00
|
|
|
bf_set(bloom->a, (hash % bloom->m));
|
2013-08-04 22:01:11 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-09-17 19:54:40 +02:00
|
|
|
bool bloom_check(bloom_t *bloom, const uint8_t *buf, size_t len)
|
2013-08-04 22:01:11 +02:00
|
|
|
{
|
2014-08-11 19:51:23 +02:00
|
|
|
for (size_t n = 0; n < bloom->k; n++) {
|
|
|
|
uint32_t hash = bloom->hash[n](buf, len);
|
2013-08-04 22:01:11 +02:00
|
|
|
|
2015-09-01 21:42:33 +02:00
|
|
|
if (!(bf_isset(bloom->a, (hash % bloom->m)))) {
|
2013-08-04 22:01:11 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true; /* ? */
|
|
|
|
}
|