summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorlucasew <lucas59356@gmail.com>2023-11-10 14:40:00 -0300
committerwoojiq <yurii.shymon@gmail.com>2024-06-28 20:53:53 +0300
commit52cc703bba09dd314b1a09f45ce59c67a3919bb8 (patch)
treec3e9899fb89d84d70597330e93d93200fc1b1c55 /lib
parentgitignore: add .helix config directory (diff)
downloadnixpkgs-52cc703bba09dd314b1a09f45ce59c67a3919bb8.tar.gz
lib: add fromHexString
Co-authored-by: lucasew <lucas59356@gmail.com>
Diffstat (limited to 'lib')
-rw-r--r--lib/default.nix2
-rw-r--r--lib/tests/misc.nix16
-rw-r--r--lib/trivial.nix26
3 files changed, 43 insertions, 1 deletions
diff --git a/lib/default.nix b/lib/default.nix
index 9c6f886c9ee4..b209544050cc 100644
--- a/lib/default.nix
+++ b/lib/default.nix
@@ -73,7 +73,7 @@ let
info showWarnings nixpkgsVersion version isInOldestRelease
mod compare splitByAndCompare seq deepSeq lessThan add sub
functionArgs setFunctionArgs isFunction toFunction mirrorFunctionArgs
- toHexString toBaseDigits inPureEvalMode isBool isInt pathExists
+ fromHexString toHexString toBaseDigits inPureEvalMode isBool isInt pathExists
genericClosure readFile;
inherit (self.fixedPoints) fix fix' converge extends composeExtensions
composeManyExtensions makeExtensible makeExtensibleWithCustomName;
diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix
index 408ea5416293..dd12923e636e 100644
--- a/lib/tests/misc.nix
+++ b/lib/tests/misc.nix
@@ -102,6 +102,7 @@ let
testAllTrue
toBaseDigits
toHexString
+ fromHexString
toInt
toIntBase10
toShellVars
@@ -286,6 +287,21 @@ runTests {
expected = "FA";
};
+ testFromHexStringFirstExample = {
+ expr = fromHexString "FF";
+ expected = 255;
+ };
+
+ testFromHexStringSecondExample = {
+ expr = fromHexString (builtins.hashString "sha256" "test");
+ expected = 9223372036854775807;
+ };
+
+ testFromHexStringWithPrefix = {
+ expr = fromHexString "0Xf";
+ expected = 15;
+ };
+
testToBaseDigits = {
expr = toBaseDigits 2 6;
expected = [ 1 1 0 ];
diff --git a/lib/trivial.nix b/lib/trivial.nix
index 20a3ffebbc2b..9ac996881df7 100644
--- a/lib/trivial.nix
+++ b/lib/trivial.nix
@@ -1075,6 +1075,32 @@ in {
else k: v;
/**
+ Convert a hexadecimal string to it's integer representation.
+
+ # Type
+
+ ```
+ fromHexString :: String -> [ String ]
+ ```
+
+ # Examples
+
+ ```nix
+ fromHexString "FF"
+ => 255
+
+ fromHexString (builtins.hashString "sha256" "test")
+ => 9223372036854775807
+ ```
+ */
+ fromHexString = value:
+ let
+ noPrefix = lib.strings.removePrefix "0x" (lib.strings.toLower value);
+ in let
+ parsed = builtins.fromTOML "v=0x${noPrefix}";
+ in parsed.v;
+
+ /**
Convert the given positive integer to a string of its hexadecimal
representation. For example: