mirror of
https://github.com/foo-dogsquared/nixos-config.git
synced 2025-02-25 06:19:00 +00:00
bahaghari/lib: init hex.pad
This commit is contained in:
parent
fe4f1d1ae9
commit
8cb22268af
@ -31,4 +31,31 @@ rec {
|
||||
*/
|
||||
isHexString = hex:
|
||||
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;
|
||||
}
|
||||
|
@ -37,4 +37,19 @@ pkgs.lib.runTests {
|
||||
expr = lib.hex.isHexString "WHAT IS THIS";
|
||||
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";
|
||||
};
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user