lib.rs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #![no_std]
  2. pub mod bloom_filter {
  3. use konst::primitive::{parse_usize, parse_u32};
  4. use konst::unwrap_ctx;
  5. use konst::option::unwrap_or;
  6. pub const ADDRESS_BITS: usize = unwrap_ctx!(parse_usize(unwrap_or!(option_env!("BLOOMFILTER_ADDRESS_BITS"), "30"))); // default = 0x1E = 30
  7. pub const BITS: usize = 1 << ADDRESS_BITS; // default = 0x40_000_000 = 128MB
  8. pub const ADDRESS_MASK: usize = BITS - 1;
  9. pub const WORD_BITS: usize = 0x8; // 8
  10. pub type WordType = u8;
  11. pub const ADDRESS_BITS_WORD: usize = 0x3; // log_2(0x8)
  12. pub const ADDRESS_MASK_WORD: usize = WORD_BITS - 1; // 0x7
  13. pub const ADDRESS_BITS_CHUNK: usize = unwrap_ctx!(parse_usize(unwrap_or!(option_env!("BLOOMFILTER_ADDRESS_BITS_CHUNK"), "18"))); // default = 0x12 = 18 = log_2(32KB)
  14. pub const CHUNK_BITS: usize = 1 << ADDRESS_BITS_CHUNK; // default = 0x40000 = 32KB (per-cpu map value size limit)
  15. pub const CHUNK_BYTES: usize = CHUNK_BITS >> 0x3;
  16. pub const CHUNK_SIZE: usize = CHUNK_BITS >> ADDRESS_BITS_WORD; // WORD_SIZE * CHUNK_SIZE = 32Kb
  17. pub type ChunkType = [WordType; CHUNK_SIZE];
  18. pub const ADDRESS_MASK_CHUNK: usize = CHUNK_BITS - 1;
  19. pub const BUFFER_SIZE: usize = BITS >> ADDRESS_BITS_WORD; // 0x20_0000
  20. pub const MAP_SIZE: usize = BITS >> ADDRESS_BITS_CHUNK;
  21. pub const HASH_COUNT: u32 = unwrap_ctx!(parse_u32(unwrap_or!(option_env!("BLOOMFILTER_HASH_COUNT"), "10")));
  22. // Hashing based on jhash.h from kernel // TODO improve reference
  23. const HASH_INITVAL: u32 = 0xdeadbeef;
  24. #[inline(always)]
  25. pub fn hash(key: u32, initial_value: u32) -> u32 {
  26. let mut b = HASH_INITVAL.wrapping_add(initial_value);
  27. let mut c = b;
  28. let mut a = key.wrapping_add(b);
  29. c ^= b;
  30. c = c.wrapping_sub(b.rotate_left(14));
  31. a ^= c;
  32. a = a.wrapping_sub(c.rotate_left(11));
  33. b ^= a;
  34. b = b.wrapping_sub(a.rotate_left(25));
  35. c ^= b;
  36. c = c.wrapping_sub(b.rotate_left(16));
  37. a ^= c;
  38. a = a.wrapping_sub(c.rotate_left(4));
  39. b ^= a;
  40. b = b.wrapping_sub(a.rotate_left(14));
  41. c ^= b;
  42. c = c.wrapping_sub(b.rotate_left(24));
  43. return c & ADDRESS_MASK as u32;
  44. }
  45. }