mirror of
https://github.com/NixOS/nixpkgs.git
synced 2025-06-10 03:23:29 +03:00
lib.strings: fix negative number handling for toInt
and toIntBase10
The previous version would be unstable due to an input validation regex not expecting a '-' in front of the number.
This commit is contained in:
parent
2bb2eec813
commit
62e863e98c
2 changed files with 11 additions and 6 deletions
|
@ -807,9 +807,9 @@ rec {
|
||||||
*/
|
*/
|
||||||
toInt = str:
|
toInt = str:
|
||||||
let
|
let
|
||||||
# RegEx: Match any leading whitespace, then any digits, and finally match any trailing
|
# RegEx: Match any leading whitespace, possibly a '-', one or more digits,
|
||||||
# whitespace.
|
# and finally match any trailing whitespace.
|
||||||
strippedInput = match "[[:space:]]*([[:digit:]]+)[[:space:]]*" str;
|
strippedInput = match "[[:space:]]*(-?[[:digit:]]+)[[:space:]]*" str;
|
||||||
|
|
||||||
# RegEx: Match a leading '0' then one or more digits.
|
# RegEx: Match a leading '0' then one or more digits.
|
||||||
isLeadingZero = match "0[[:digit:]]+" (head strippedInput) == [];
|
isLeadingZero = match "0[[:digit:]]+" (head strippedInput) == [];
|
||||||
|
@ -858,9 +858,10 @@ rec {
|
||||||
*/
|
*/
|
||||||
toIntBase10 = str:
|
toIntBase10 = str:
|
||||||
let
|
let
|
||||||
# RegEx: Match any leading whitespace, then match any zero padding, capture any remaining
|
# RegEx: Match any leading whitespace, then match any zero padding,
|
||||||
# digits after that, and finally match any trailing whitespace.
|
# capture possibly a '-' followed by one or more digits,
|
||||||
strippedInput = match "[[:space:]]*0*([[:digit:]]+)[[:space:]]*" str;
|
# and finally match any trailing whitespace.
|
||||||
|
strippedInput = match "[[:space:]]*0*(-?[[:digit:]]+)[[:space:]]*" str;
|
||||||
|
|
||||||
# RegEx: Match at least one '0'.
|
# RegEx: Match at least one '0'.
|
||||||
isZero = match "0+" (head strippedInput) == [];
|
isZero = match "0+" (head strippedInput) == [];
|
||||||
|
|
|
@ -339,6 +339,8 @@ runTests {
|
||||||
(0 == toInt " 0")
|
(0 == toInt " 0")
|
||||||
(0 == toInt "0 ")
|
(0 == toInt "0 ")
|
||||||
(0 == toInt " 0 ")
|
(0 == toInt " 0 ")
|
||||||
|
(-1 == toInt "-1")
|
||||||
|
(-1 == toInt " -1 ")
|
||||||
];
|
];
|
||||||
|
|
||||||
testToIntFails = testAllTrue [
|
testToIntFails = testAllTrue [
|
||||||
|
@ -383,6 +385,8 @@ runTests {
|
||||||
(0 == toIntBase10 " 000000")
|
(0 == toIntBase10 " 000000")
|
||||||
(0 == toIntBase10 "000000 ")
|
(0 == toIntBase10 "000000 ")
|
||||||
(0 == toIntBase10 " 000000 ")
|
(0 == toIntBase10 " 000000 ")
|
||||||
|
(-1 == toIntBase10 "-1")
|
||||||
|
(-1 == toIntBase10 " -1 ")
|
||||||
];
|
];
|
||||||
|
|
||||||
testToIntBase10Fails = testAllTrue [
|
testToIntBase10Fails = testAllTrue [
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue