BitMaps.sol 1.5 KB

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