BitMaps.sol 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts v4.4.1 (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. * Largelly 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(
  24. BitMap storage bitmap,
  25. uint256 index,
  26. bool value
  27. ) internal {
  28. if (value) {
  29. set(bitmap, index);
  30. } else {
  31. unset(bitmap, index);
  32. }
  33. }
  34. /**
  35. * @dev Sets the bit at `index`.
  36. */
  37. function set(BitMap storage bitmap, uint256 index) internal {
  38. uint256 bucket = index >> 8;
  39. uint256 mask = 1 << (index & 0xff);
  40. bitmap._data[bucket] |= mask;
  41. }
  42. /**
  43. * @dev Unsets the bit at `index`.
  44. */
  45. function unset(BitMap storage bitmap, uint256 index) internal {
  46. uint256 bucket = index >> 8;
  47. uint256 mask = 1 << (index & 0xff);
  48. bitmap._data[bucket] &= ~mask;
  49. }
  50. }