summaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
authorJacob Abel <jacobabel@nullpo.dev>2022-05-21 22:34:11 -0400
committerJacob Abel <jacobabel@nullpo.dev>2022-10-23 17:50:20 -0400
commitfebff1dccd2c173472fe4a6bed2e620429c5b1ba (patch)
tree4d66beccb6704f2f897b5de7afcf22aa3d8ca70b /lib
parent86ad681303d9bc567cca762b239f3fde0b951d64 (diff)
lib/strings: allow toInt to parse zero-padded strings
Diffstat (limited to 'lib')
-rw-r--r--lib/strings.nix20
-rw-r--r--lib/tests/misc.nix28
2 files changed, 44 insertions, 4 deletions
diff --git a/lib/strings.nix b/lib/strings.nix
index be217cb06469..8f3568fc1fc5 100644
--- a/lib/strings.nix
+++ b/lib/strings.nix
@@ -792,15 +792,27 @@ rec {
=> 1337
toInt "-4"
=> -4
+ toInt " 123 "
+ => 123
+ toInt "00024"
+ => 24
toInt "3.14"
=> error: floating point JSON numbers are not supported
*/
# Obviously, it is a bit hacky to use fromJSON this way.
toInt = str:
- let may_be_int = fromJSON str; in
- if isInt may_be_int
- then may_be_int
- else throw "Could not convert ${str} to int.";
+ let
+ strippedInput = match "[[:space:]]*(0*)(.*)" str;
+ isNonZeroEmpty = match "[[:space:]]*" (lib.last strippedInput) == [];
+ isZeroNonEmpty = head strippedInput != "";
+ mayBeInt = fromJSON (lib.last strippedInput);
+ in
+ if isNonZeroEmpty && isZeroNonEmpty
+ then 0
+ else
+ if isInt mayBeInt
+ then mayBeInt
+ else throw "Could not convert ${str} to int.";
/* Read a list of paths from `file`, relative to the `rootPath`.
Lines beginning with `#` are treated as comments and ignored.
diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix
index 8e0cf1f45bb6..ef4483219f7e 100644
--- a/lib/tests/misc.nix
+++ b/lib/tests/misc.nix
@@ -327,6 +327,34 @@ runTests {
expected = "Hello\\x20World";
};
+ testToInt = testAllTrue [
+ # Naive
+ (123 == toInt "123")
+ (0 == toInt "0")
+ # Whitespace Padding
+ (123 == toInt " 123")
+ (123 == toInt "123 ")
+ (123 == toInt " 123 ")
+ (123 == toInt " 123 ")
+ (0 == toInt " 0")
+ (0 == toInt "0 ")
+ (0 == toInt " 0 ")
+ # Zero Padding
+ (123 == toInt "0123")
+ (123 == toInt "0000123")
+ (0 == toInt "000000")
+ # Whitespace and Zero Padding
+ (123 == toInt " 0123")
+ (123 == toInt "0123 ")
+ (123 == toInt " 0123 ")
+ (123 == toInt " 0000123")
+ (123 == toInt "0000123 ")
+ (123 == toInt " 0000123 ")
+ (0 == toInt " 000000")
+ (0 == toInt "000000 ")
+ (0 == toInt " 000000 ")
+ ];
+
# LISTS
testFilter = {