lib/strings: add a `toInt` helper (close #11242)
While the function itself is pretty easy, it's not straitforward to find a way to convert string to int with nix.
This commit is contained in:
parent
882344e480
commit
1cdacc6aa2
|
@ -223,4 +223,12 @@ rec {
|
|||
# Check whether a value is a store path.
|
||||
isStorePath = x: builtins.substring 0 1 (toString x) == "/" && dirOf (builtins.toPath x) == builtins.storeDir;
|
||||
|
||||
# Convert string to int
|
||||
# Obviously, it is a bit hacky to use fromJSON that way.
|
||||
toInt = str:
|
||||
let may_be_int = builtins.fromJSON str; in
|
||||
if builtins.isInt may_be_int
|
||||
then may_be_int
|
||||
else throw "Could not convert ${str} to int.";
|
||||
|
||||
}
|
||||
|
|
|
@ -110,4 +110,14 @@ runTests {
|
|||
expected = [2 30 40 42];
|
||||
};
|
||||
|
||||
testToIntShouldConvertStringToInt = {
|
||||
expr = toInt "27";
|
||||
expected = 27;
|
||||
};
|
||||
|
||||
testToIntShouldThrowErrorIfItCouldNotConvertToInt = {
|
||||
expr = builtins.tryEval (toInt "\"foo\"");
|
||||
expected = { success = false; value = false; };
|
||||
};
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue