forked from Uniswap/v4-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSafeCast.sol
36 lines (32 loc) · 1.36 KB
/
SafeCast.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y <= uint256(type(int256).max));
z = int256(y);
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(uint256 y) internal pure returns (int128 z) {
require(y <= uint128(type(int128).max));
z = int128(int256(y));
}
}