bahaghari/lib: init hex.pad

This commit is contained in:
Gabriel Arazas 2024-02-24 21:36:51 +08:00
parent fe4f1d1ae9
commit 8cb22268af
No known key found for this signature in database
GPG Key ID: ADE0C41DAB221FCC
2 changed files with 42 additions and 0 deletions

View File

@ -31,4 +31,31 @@ rec {
*/ */
isHexString = hex: isHexString = hex:
builtins.match "[A-Fa-f0-9]+" hex != null; builtins.match "[A-Fa-f0-9]+" hex != null;
/* Left pads the given hex number with the given number of max amount of
digits. It will throw an error if it's not a hex string.
Type: pad :: Int -> String -> String
Example:
pad 2 "A"
=> "0A"
pad 1 "ABC"
=> "ABC"
pad -2 "ABC"
=> "ABC"
*/
pad = n: hex:
let
strLength = pkgs.lib.stringLength hex;
reqWidth = n - strLength;
components = pkgs.lib.genList (_: "0") reqWidth ++ [ hex ];
in
assert pkgs.lib.assertMsg (isHexString hex)
"bahaghariLib.hex.pad: given hex number (${hex}) is not valid";
if (reqWidth <= 0)
then hex
else pkgs.lib.concatStringsSep "" components;
} }

View File

@ -37,4 +37,19 @@ pkgs.lib.runTests {
expr = lib.hex.isHexString "WHAT IS THIS"; expr = lib.hex.isHexString "WHAT IS THIS";
expected = false; expected = false;
}; };
testHexPad = {
expr = lib.hex.pad 5 "A";
expected = "0000A";
};
testHexPadWithLowerMaxDigits = {
expr = lib.hex.pad 1 "9AC";
expected = "9AC";
};
testHexPadWithNegativeDigits = {
expr = lib.hex.pad -5 "A42C";
expected = "A42C";
};
} }