git.iko.soy/typeable/nixpkgs
on master help sign in
lib: add the toHex and toBase utility functions

`toHex` converts the given positive integer to a string of the hexadecimal representation of that integer. For example: ``` toHex 0 => "0" toHex 16 => "10" toHex 250 => "FA" ``` `toBase base i` converts the positive integer `i` to a list of it digits in the given `base`. For example: ``` toBase 10 123 => [ 1 2 3 ] toBase 2 6 => [ 1 1 0 ] toBase 16 250 => [ 15 10 ] ```

commit00022fbeda385d7b6ae2eee44f07eecfc6d92015 authorBas van Dijk <v.dijk.bas@gmail.com> dateMon 20 Apr 2020, 12:00 (7 years ago) parentd0c12dc
3 files changed+62−1
lib/default.nix+1−1 lib/tests/misc.nix+10 lib/trivial.nix+51
lib/default.nix+1−1
@@ -67,7 +67,7 @@ let
6767 inherit (trivial) id const pipe concat or and bitAnd bitOr bitXor
6868 bitNot boolToString mergeAttrs flip mapNullable inNixShell min max
6969 importJSON warn info showWarnings nixpkgsVersion version mod compare
70− splitByAndCompare functionArgs setFunctionArgs isFunction;
70+ splitByAndCompare functionArgs setFunctionArgs isFunction toHex toBase;
7171 inherit (fixedPoints) fix fix' converge extends composeExtensions
7272 makeExtensible makeExtensibleWithCustomName;
7373 inherit (attrsets) attrByPath hasAttrByPath setAttrByPath
lib/tests/misc.nix+10
@@ -102,6 +102,16 @@ runTests {
102102 expected = 9;
103103 };
104104
105+ testToHex = {
106+ expr = toHex 250;
107+ expected = "FA";
108+ };
109+
110+ testToBase = {
111+ expr = toBase 2 6;
112+ expected = [ 1 1 0 ];
113+ };
114+
105115# STRINGS
106116
107117 testConcatMapStrings = {
lib/trivial.nix+51
@@ -332,4 +332,55 @@ rec {
332332 */
333333 isFunction = f: builtins.isFunction f ||
334334 (f ? __functor && isFunction (f.__functor f));
335+
336+ /* Convert the given positive integer to a string of its hexadecimal
337+ representation. For example:
338+
339+ toHex 0 => "0"
340+
341+ toHex 16 => "10"
342+
343+ toHex 250 => "FA"
344+ */
345+ toHex = i:
346+ let
347+ toHexDigit = d:
348+ if d < 10
349+ then toString d
350+ else
351+ {
352+ "10" = "A";
353+ "11" = "B";
354+ "12" = "C";
355+ "13" = "D";
356+ "14" = "E";
357+ "15" = "F";
358+ }.${toString d};
359+ in
360+ lib.concatMapStrings toHexDigit (toBase 16 i);
361+
362+ /* `toBase base i` converts the positive integer i to a list of its
363+ digits in the given base. For example:
364+
365+ toBase 10 123 => [ 1 2 3 ]
366+
367+ toBase 2 6 => [ 1 1 0 ]
368+
369+ toBase 16 250 => [ 15 10 ]
370+ */
371+ toBase = base: i:
372+ let
373+ go = i:
374+ if i < base
375+ then [i]
376+ else
377+ let
378+ r = i - ((i / base) * base);
379+ q = (i - r) / base;
380+ in
381+ [r] ++ go q;
382+ in
383+ assert (base >= 2);
384+ assert (i >= 0);
385+ lib.reverseList (go i);
335386}