summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorRobert Hensing <roberth@users.noreply.github.com>2022-12-11 02:26:42 +0100
committerGitHub <noreply@github.com>2022-12-11 02:26:42 +0100
commitefa1140e8344212601b83182247b95b4b65fb00a (patch)
tree8121be1ffe8bfa5d5f5d8c3407a7b92667fe3e94 /lib
parentMerge pull request #205577 from astro/wander (diff)
parentlib.strings: fix negative number handling for `toInt` and `toIntBase10` (diff)
downloadnixpkgs-efa1140e8344212601b83182247b95b4b65fb00a.tar.gz
Merge pull request #205457 from h7x4/lib-strings-toInt-broken-for-negative-numbers
lib.strings: fix negative number handling for `toInt` and `toIntBase10`
Diffstat (limited to 'lib')
-rw-r--r--lib/strings.nix13
-rw-r--r--lib/tests/misc.nix4
2 files changed, 11 insertions, 6 deletions
diff --git a/lib/strings.nix b/lib/strings.nix
index 9a4f29380d0d..376c537287e9 100644
--- a/lib/strings.nix
+++ b/lib/strings.nix
@@ -860,9 +860,9 @@ rec {
*/
toInt = str:
let
- # RegEx: Match any leading whitespace, then any digits, and finally match any trailing
- # whitespace.
- strippedInput = match "[[:space:]]*([[:digit:]]+)[[:space:]]*" str;
+ # RegEx: Match any leading whitespace, possibly a '-', one or more digits,
+ # and finally match any trailing whitespace.
+ strippedInput = match "[[:space:]]*(-?[[:digit:]]+)[[:space:]]*" str;
# RegEx: Match a leading '0' then one or more digits.
isLeadingZero = match "0[[:digit:]]+" (head strippedInput) == [];
@@ -911,9 +911,10 @@ rec {
*/
toIntBase10 = str:
let
- # RegEx: Match any leading whitespace, then match any zero padding, capture any remaining
- # digits after that, and finally match any trailing whitespace.
- strippedInput = match "[[:space:]]*0*([[:digit:]]+)[[:space:]]*" str;
+ # RegEx: Match any leading whitespace, then match any zero padding,
+ # capture possibly a '-' followed by one or more digits,
+ # and finally match any trailing whitespace.
+ strippedInput = match "[[:space:]]*0*(-?[[:digit:]]+)[[:space:]]*" str;
# RegEx: Match at least one '0'.
isZero = match "0+" (head strippedInput) == [];
diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix
index 648c05ab3572..c719fcf5d4fa 100644
--- a/lib/tests/misc.nix
+++ b/lib/tests/misc.nix
@@ -339,6 +339,8 @@ runTests {
(0 == toInt " 0")
(0 == toInt "0 ")
(0 == toInt " 0 ")
+ (-1 == toInt "-1")
+ (-1 == toInt " -1 ")
];
testToIntFails = testAllTrue [
@@ -383,6 +385,8 @@ runTests {
(0 == toIntBase10 " 000000")
(0 == toIntBase10 "000000 ")
(0 == toIntBase10 " 000000 ")
+ (-1 == toIntBase10 "-1")
+ (-1 == toIntBase10 " -1 ")
];
testToIntBase10Fails = testAllTrue [