Packing.sol 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.20;
  3. /**
  4. * @dev Helper library packing and unpacking multiple values into bytes32
  5. */
  6. library Packing {
  7. type Uint128x2 is bytes32;
  8. /// @dev Cast a bytes32 into a Uint128x2
  9. function asUint128x2(bytes32 self) internal pure returns (Uint128x2) {
  10. return Uint128x2.wrap(self);
  11. }
  12. /// @dev Cast a Uint128x2 into a bytes32
  13. function asBytes32(Uint128x2 self) internal pure returns (bytes32) {
  14. return Uint128x2.unwrap(self);
  15. }
  16. /// @dev Pack two uint128 into a Uint128x2
  17. function pack(uint128 first128, uint128 second128) internal pure returns (Uint128x2) {
  18. return Uint128x2.wrap(bytes32(bytes16(first128)) | bytes32(uint256(second128)));
  19. }
  20. /// @dev Split a Uint128x2 into two uint128
  21. function split(Uint128x2 self) internal pure returns (uint128, uint128) {
  22. return (first(self), second(self));
  23. }
  24. /// @dev Get the first element of a Uint128x2 counting from higher to lower bytes
  25. function first(Uint128x2 self) internal pure returns (uint128) {
  26. return uint128(bytes16(Uint128x2.unwrap(self)));
  27. }
  28. /// @dev Get the second element of a Uint128x2 counting from higher to lower bytes
  29. function second(Uint128x2 self) internal pure returns (uint128) {
  30. return uint128(uint256(Uint128x2.unwrap(self)));
  31. }
  32. }