Add Packing library (#4992)

Co-authored-by: ernestognw <ernestognw@gmail.com>
This commit is contained in:
Hadrien Croubois
2024-04-05 14:59:18 +02:00
committed by GitHub
parent 90fd7cc7dd
commit f8c2e1035e
6 changed files with 103 additions and 0 deletions

View File

@ -0,0 +1,40 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @dev Helper library packing and unpacking multiple values into bytes32
*/
library Packing {
type Uint128x2 is bytes32;
/// @dev Cast a bytes32 into a Uint128x2
function asUint128x2(bytes32 self) internal pure returns (Uint128x2) {
return Uint128x2.wrap(self);
}
/// @dev Cast a Uint128x2 into a bytes32
function asBytes32(Uint128x2 self) internal pure returns (bytes32) {
return Uint128x2.unwrap(self);
}
/// @dev Pack two uint128 into a Uint128x2
function pack(uint128 first128, uint128 second128) internal pure returns (Uint128x2) {
return Uint128x2.wrap(bytes32(bytes16(first128)) | bytes32(uint256(second128)));
}
/// @dev Split a Uint128x2 into two uint128
function split(Uint128x2 self) internal pure returns (uint128, uint128) {
return (first(self), second(self));
}
/// @dev Get the first element of a Uint128x2 counting from higher to lower bytes
function first(Uint128x2 self) internal pure returns (uint128) {
return uint128(bytes16(Uint128x2.unwrap(self)));
}
/// @dev Get the second element of a Uint128x2 counting from higher to lower bytes
function second(Uint128x2 self) internal pure returns (uint128) {
return uint128(uint256(Uint128x2.unwrap(self)));
}
}

View File

@ -33,6 +33,7 @@ Miscellaneous contracts and libraries containing utility functions you can use t
* {StorageSlot}: Methods for accessing specific storage slots formatted as common primitive types. Also include primitives for reading from and writing to transient storage (only value types are currently supported).
* {Multicall}: Abstract contract with an utility to allow batching together multiple calls in a single transaction. Useful for allowing EOAs to perform multiple operations at once.
* {Context}: An utility for abstracting the sender and calldata in the current execution context.
* {Packing}: A library for packing and unpacking multiple values into bytes32
* {Panic}: A library to revert with https://docs.soliditylang.org/en/v0.8.20/control-structures.html#panic-via-assert-and-error-via-require[Solidity panic codes].
[NOTE]
@ -120,4 +121,6 @@ Ethereum contracts have no native concept of an interface, so applications must
{{Context}}
{{Packing}}
{{Panic}}