数据结构—哈希+位图->布隆过滤器(数据类型char*)

#include
#include
#include"BitMap.h"

typedef const char* KeyType;
typedef struct BloomFilter
{
    BitMap _bm;
}BloomFilter;

void BloomFilterInit(BloomFilter* bf, size_t range);//制表
void BloomFilterSet(BloomFilter* bf, KeyType key);//插入
int BloomFilterTest(BloomFilter* bf, KeyType key);//查找
void BloomFilterReset(BloomFilter* bf, KeyType key);//不支持
void BloomFilterDestory(BloomFilter* bf); //销毁

//第一种哈希函数
size_t SDBMHash(const char *str)
{
    register size_t hash = 0;
    while (size_t ch = (size_t)*str++)
    {
        hash = 65599 * hash + ch;
    }
    return hash;
}
size_t BFHashFunc1(KeyType key)
{
    return SDBMHash(key);

}

//第二种哈希函数
size_t APHash(const char* str)
{
    register size_t hash = 0;
    size_t ch;
    for (long i = 0; ch = (size_t)*str++; i++)
    {
        if ((i & 1) == 0)
        {
            hash ^= ((hash << 7) ^ ch ^ (hash >> 3));
        }
        else
        {
            hash ^= (~((hash << 11) ^ ch ^ (hash >> 5)));
        }
    }
    return hash;
}
size_t BFHashFunc2(KeyType key)
{
    return APHash(key);
}

//第三种哈希函数
size_t BKDRHash(const char* str)
{
    register size_t hash = 0;
    while (size_t ch = (size_t)*str++)
    {
        hash = hash * 131 + ch;          
    }
    return hash;
}
size_t BFHashFunc3(KeyType key)
{
    return BKDRHash(key);
}
void BloomFilterInit(BloomFilter* bf, size_t range)
{
    assert(bf);
    BitMapInit(&(bf->_bm), range*4.5);
}

void BloomFilterSet(BloomFilter* bf, KeyType key)
{
    size_t hash1 = BFHashFunc1(key) % bf->_bm._range;
    BitMapSet(&bf->_bm, hash1);

    size_t hash2 = BFHashFunc2(key) % bf->_bm._range;
    BitMapSet(&bf->_bm, hash2);

    size_t hash3 = BFHashFunc3(key) % bf->_bm._range;
    BitMapSet(&bf->_bm, hash3);

}

int BloomFilterTest(BloomFilter* bf, KeyType key)
{
    size_t hash1 = BFHashFunc1(key) % bf->_bm._range;
    if (BitMapTest(&bf->_bm, hash1) == 0)
    {
        return 0;
    }
    size_t hash2 = BFHashFunc2(key) % bf->_bm._range;
    if (BitMapTest(&bf->_bm, hash2) == 0)
    {
        return 0;
    }
    size_t hash3 = BFHashFunc3(key) % bf->_bm._range;
    if (BitMapTest(&bf->_bm, hash3) == 0)
    {
        return 0;
    }
    return 1;
}

void BloomFilterDestory(BloomFilter* bf)
{
    BitMapDestory(&bf->_bm);
}

你可能感兴趣的:(数据结构—哈希+位图->布隆过滤器(数据类型char*))