summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorh7x4 <h7x4@nani.wtf>2022-12-10 13:02:40 +0100
committergithub-actions[bot] <github-actions[bot]@users.noreply.github.com>2022-12-11 01:33:42 +0000
commit2f096450b9150014fda672d317e55aa5a4283257 (patch)
treeb6b783236cd016003baf7063275a68f584b8e3b0
parentMerge pull request #205576 from NixOS/backport-205573-to-release-22.11 (diff)
downloadnixpkgs-origin/backport-205457-to-release-22.11.tar.gz
lib.strings: fix negative number handling for `toInt` and `toIntBase10`origin/backport-205457-to-release-22.11
The previous version would be unstable due to an input validation regex not expecting a '-' in front of the number. (cherry picked from commit 62e863e98c8f5c22c0dd4ee3845613a858262b4c)
-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 b5f5a4d9060b..a5c3965f8f1a 100644
--- a/lib/strings.nix
+++ b/lib/strings.nix
@@ -807,9 +807,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) == [];
@@ -858,9 +858,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 b73da4f1010d..9bdc30d85d44 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 [