lib/strings: allow toInt to parse zero-padded strings
This commit is contained in:
parent
86ad681303
commit
febff1dccd
2 changed files with 44 additions and 4 deletions
|
@ -792,14 +792,26 @@ 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
|
||||
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`.
|
||||
|
|
|
@ -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 = {
|
||||
|
|
Loading…
Reference in a new issue