General Purpose library for Freestanding C++ and POSIX systems
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.2 KiB

  1. #pragma once
  2. #include <gp/algorithms/foreach.hpp>
  3. #include <gp/algorithms/tmp_manip.hpp>
  4. #include <gp/containers/array.hpp>
  5. #include <atomic>
  6. #include <stdint.h>
  7. namespace gp {
  8. template<typename hash_type = uint64_t, uint8_t magnitude = 19, bool threading = false>
  9. class bloomfilter {
  10. constexpr static size_t phys_size = (1ull << magnitude) / 32ull;
  11. gp::array<
  12. typename gp::either< threading,
  13. std::atomic_uint32_t,
  14. uint32_t
  15. >::type,
  16. phys_size
  17. > data;
  18. template<typename T>
  19. static void set_bit(T* value, const int v_pos) {
  20. *value |= (1ull << v_pos);
  21. }
  22. template<typename T>
  23. static bool get_bit(T* value, const int v_pos) {
  24. return (*value >> v_pos) & 1ull;
  25. }
  26. public:
  27. bloomfilter()
  28. {
  29. fill(data, 0);
  30. }
  31. void set_hash(hash_type v)
  32. {
  33. const size_t modulo = v & ((1ull << magnitude)-1ull);
  34. const size_t p_pos = modulo / 32;
  35. const size_t v_pos = modulo % 32;
  36. set_bit(&data[p_pos], v_pos);
  37. }
  38. bool test_hash(hash_type v)
  39. {
  40. const size_t modulo = v & ((1ull << magnitude)-1ull);
  41. const size_t p_pos = modulo / 32;
  42. const size_t v_pos = modulo % 32;
  43. return get_bit(&data[p_pos], v_pos);
  44. }
  45. };
  46. }