diff options
author | Jacob Abel <jacobabel@nullpo.dev> | 2022-05-23 03:39:48 -0400 |
---|---|---|
committer | Jacob Abel <jacobabel@nullpo.dev> | 2022-10-23 17:50:23 -0400 |
commit | 3d196a5f2a72595b14c439a9b4aba7737c0f1ebe (patch) | |
tree | 48c839f091c9f1c56ad2bc041150201b87a3c64c /lib/strings.nix | |
parent | febff1dccd2c173472fe4a6bed2e620429c5b1ba (diff) | |
download | nixpkgs-3d196a5f2a72595b14c439a9b4aba7737c0f1ebe.tar nixpkgs-3d196a5f2a72595b14c439a9b4aba7737c0f1ebe.tar.gz nixpkgs-3d196a5f2a72595b14c439a9b4aba7737c0f1ebe.tar.bz2 nixpkgs-3d196a5f2a72595b14c439a9b4aba7737c0f1ebe.tar.lz nixpkgs-3d196a5f2a72595b14c439a9b4aba7737c0f1ebe.tar.xz nixpkgs-3d196a5f2a72595b14c439a9b4aba7737c0f1ebe.tar.zst nixpkgs-3d196a5f2a72595b14c439a9b4aba7737c0f1ebe.zip |
lib/strings: Update toInt to handle intermixed ws and zeros. Added tests
Diffstat (limited to 'lib/strings.nix')
-rw-r--r-- | lib/strings.nix | 20 |
1 files changed, 13 insertions, 7 deletions
diff --git a/lib/strings.nix b/lib/strings.nix index 8f3568fc1fc..c6269e755e2 100644 --- a/lib/strings.nix +++ b/lib/strings.nix @@ -802,16 +802,22 @@ rec { # Obviously, it is a bit hacky to use fromJSON this way. toInt = str: let - strippedInput = match "[[:space:]]*(0*)(.*)" str; - isNonZeroEmpty = match "[[:space:]]*" (lib.last strippedInput) == []; - isZeroNonEmpty = head strippedInput != ""; - mayBeInt = fromJSON (lib.last strippedInput); + # RegEx: Match any leading whitespace, then any zero padding, and capture any remaining + # digits after that, and finally match any trailing whitespace. + strippedInput = match "[[:space:]]*0*([[:digit:]]+)[[:space:]]*" str; + + # RegEx: Match any leading whitespace, at least one '0', and any trailing whitespace. + isZero = match "[[:space:]]*0+[[:space:]]*" str == []; + + # Attempt to parse input + parsedInput = fromJSON (elemAt strippedInput 0); in - if isNonZeroEmpty && isZeroNonEmpty + # Value is zero + if isZero then 0 else - if isInt mayBeInt - then mayBeInt + if strippedInput != null && isInt parsedInput + then parsedInput else throw "Could not convert ${str} to int."; /* Read a list of paths from `file`, relative to the `rootPath`. |