lib: add fromHexString

Co-authored-by: lucasew <lucas59356@gmail.com>
This commit is contained in:
lucasew 2023-11-10 14:40:00 -03:00 committed by woojiq
parent 9cd5b7a85d
commit 52cc703bba
3 changed files with 43 additions and 1 deletions

View file

@ -73,7 +73,7 @@ let
info showWarnings nixpkgsVersion version isInOldestRelease info showWarnings nixpkgsVersion version isInOldestRelease
mod compare splitByAndCompare seq deepSeq lessThan add sub mod compare splitByAndCompare seq deepSeq lessThan add sub
functionArgs setFunctionArgs isFunction toFunction mirrorFunctionArgs functionArgs setFunctionArgs isFunction toFunction mirrorFunctionArgs
toHexString toBaseDigits inPureEvalMode isBool isInt pathExists fromHexString toHexString toBaseDigits inPureEvalMode isBool isInt pathExists
genericClosure readFile; genericClosure readFile;
inherit (self.fixedPoints) fix fix' converge extends composeExtensions inherit (self.fixedPoints) fix fix' converge extends composeExtensions
composeManyExtensions makeExtensible makeExtensibleWithCustomName; composeManyExtensions makeExtensible makeExtensibleWithCustomName;

View file

@ -102,6 +102,7 @@ let
testAllTrue testAllTrue
toBaseDigits toBaseDigits
toHexString toHexString
fromHexString
toInt toInt
toIntBase10 toIntBase10
toShellVars toShellVars
@ -286,6 +287,21 @@ runTests {
expected = "FA"; expected = "FA";
}; };
testFromHexStringFirstExample = {
expr = fromHexString "FF";
expected = 255;
};
testFromHexStringSecondExample = {
expr = fromHexString (builtins.hashString "sha256" "test");
expected = 9223372036854775807;
};
testFromHexStringWithPrefix = {
expr = fromHexString "0Xf";
expected = 15;
};
testToBaseDigits = { testToBaseDigits = {
expr = toBaseDigits 2 6; expr = toBaseDigits 2 6;
expected = [ 1 1 0 ]; expected = [ 1 1 0 ];

View file

@ -1074,6 +1074,32 @@ in {
then v then v
else k: v; 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 Convert the given positive integer to a string of its hexadecimal
representation. For example: representation. For example: