Memory.sol 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.20;
  3. /**
  4. * @dev Utilities to manipulate memory.
  5. *
  6. * Memory is a contiguous and dynamic byte array in which Solidity stores non-primitive types.
  7. * This library provides functions to manipulate pointers to this dynamic array.
  8. *
  9. * WARNING: When manipulating memory, make sure to follow the Solidity documentation
  10. * guidelines for https://docs.soliditylang.org/en/v0.8.20/assembly.html#memory-safety[Memory Safety].
  11. */
  12. library Memory {
  13. type Pointer is bytes32;
  14. /// @dev Returns a `Pointer` to the current free `Pointer`.
  15. function getFreeMemoryPointer() internal pure returns (Pointer ptr) {
  16. assembly ("memory-safe") {
  17. ptr := mload(0x40)
  18. }
  19. }
  20. /**
  21. * @dev Sets the free `Pointer` to a specific value.
  22. *
  23. * WARNING: Everything after the pointer may be overwritten.
  24. **/
  25. function setFreeMemoryPointer(Pointer ptr) internal pure {
  26. assembly ("memory-safe") {
  27. mstore(0x40, ptr)
  28. }
  29. }
  30. /// @dev `Pointer` to `bytes32`. Expects a pointer to a properly ABI-encoded `bytes` object.
  31. function asBytes32(Pointer ptr) internal pure returns (bytes32) {
  32. return Pointer.unwrap(ptr);
  33. }
  34. /// @dev `bytes32` to `Pointer`. Expects a pointer to a properly ABI-encoded `bytes` object.
  35. function asPointer(bytes32 value) internal pure returns (Pointer) {
  36. return Pointer.wrap(value);
  37. }
  38. }