Counters.sol 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. pragma solidity ^0.5.7;
  2. import "../math/SafeMath.sol";
  3. /**
  4. * @title Counters
  5. * @author Matt Condon (@shrugs)
  6. * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
  7. * of elements in a mapping, issuing ERC721 ids, or counting request ids.
  8. *
  9. * Include with `using Counters for Counters.Counter;`
  10. * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath
  11. * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
  12. * directly accessed.
  13. */
  14. library Counters {
  15. using SafeMath for uint256;
  16. struct Counter {
  17. // This variable should never be directly accessed by users of the library: interactions must be restricted to
  18. // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
  19. // this feature: see https://github.com/ethereum/solidity/issues/4637
  20. uint256 _value; // default: 0
  21. }
  22. function current(Counter storage counter) internal view returns (uint256) {
  23. return counter._value;
  24. }
  25. function increment(Counter storage counter) internal {
  26. counter._value += 1;
  27. }
  28. function decrement(Counter storage counter) internal {
  29. counter._value = counter._value.sub(1);
  30. }
  31. }