BitMaps.sol 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.0;
  3. /**
  4. * @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential.
  5. * Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
  6. */
  7. library BitMaps {
  8. struct BitMap {
  9. mapping(uint256 => uint256) _data;
  10. }
  11. /**
  12. * @dev Returns whether the bit at `index` is set.
  13. */
  14. function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
  15. uint256 bucket = index / 256;
  16. uint256 mask = 1 << (index % 256);
  17. return bitmap._data[bucket] & mask != 0;
  18. }
  19. /**
  20. * @dev Sets the bit at `index` to the boolean `value`.
  21. */
  22. function setTo(
  23. BitMap storage bitmap,
  24. uint256 index,
  25. bool value
  26. ) internal {
  27. if (value) {
  28. set(bitmap, index);
  29. } else {
  30. unset(bitmap, index);
  31. }
  32. }
  33. /**
  34. * @dev Sets the bit at `index`.
  35. */
  36. function set(BitMap storage bitmap, uint256 index) internal {
  37. uint256 bucket = index / 256;
  38. uint256 mask = 1 << (index % 256);
  39. bitmap._data[bucket] |= mask;
  40. }
  41. /**
  42. * @dev Unsets the bit at `index`.
  43. */
  44. function unset(BitMap storage bitmap, uint256 index) internal {
  45. uint256 bucket = index / 256;
  46. uint256 mask = 1 << (index % 256);
  47. bitmap._data[bucket] &= ~mask;
  48. }
  49. }