Skip to content

Commit

Permalink
signed int parse
Browse files Browse the repository at this point in the history
  • Loading branch information
thedavidmeister committed Nov 1, 2024
1 parent 756ad68 commit 81bc63c
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/lib/parse/LibParseDecimal.sol
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
// SPDX-FileCopyrightText: Copyright (c) 2020 thedavidmeister
pragma solidity ^0.8.25;

import {CMASK_NEGATIVE_SIGN} from "./LibParseCMask.sol";
import {LibParseChar} from "./LibParseChar.sol";

library LibParseDecimal {
/// @notice Convert a decimal ASCII string in a memory region to an
/// 18 decimal fixed point `uint256`.
Expand Down Expand Up @@ -87,4 +90,26 @@ library LibParseDecimal {
return (1, value);
}
}

function unsafeDecimalStringToSignedInt(uint256 start, uint256 end) internal pure returns (uint256, int256) {
unchecked {
uint256 cursor = start;
uint256 isNeg = LibParseChar.isMask(cursor, end, CMASK_NEGATIVE_SIGN);
cursor += isNeg;

(uint256 success, uint256 value) = LibParseDecimal.unsafeDecimalStringToInt(cursor, end);
// Handle failure.
if (success == 0) {
return (0, 0);
}

// Handle positive value.
if (isNeg == 0) {
return (value > uint256(type(int256).max) ? 0 : 1, int256(value));
}

// Fallback to negative value.
return (value > uint256(type(int256).max) + 1 ? 0 : 1, -int256(value));
}
}
}

0 comments on commit 81bc63c

Please sign in to comment.