From 8cb22268af7889de0c96243233428e8609c5105d Mon Sep 17 00:00:00 2001 From: Gabriel Arazas Date: Sat, 24 Feb 2024 21:36:51 +0800 Subject: [PATCH] bahaghari/lib: init `hex.pad` --- subprojects/bahaghari/lib/hex.nix | 27 +++++++++++++++++++++++++ subprojects/bahaghari/tests/lib/hex.nix | 15 ++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/subprojects/bahaghari/lib/hex.nix b/subprojects/bahaghari/lib/hex.nix index 8a6b071b..cb691e7f 100644 --- a/subprojects/bahaghari/lib/hex.nix +++ b/subprojects/bahaghari/lib/hex.nix @@ -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; } diff --git a/subprojects/bahaghari/tests/lib/hex.nix b/subprojects/bahaghari/tests/lib/hex.nix index 30300471..50541193 100644 --- a/subprojects/bahaghari/tests/lib/hex.nix +++ b/subprojects/bahaghari/tests/lib/hex.nix @@ -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"; + }; }