# Credits to https://github.com/Misterio77/nix-colors/blob/b92df8f5eb1fa20d8e09810c03c9dc0d94ef2820/lib/core/conversions.nix#L87 { lib, math ? import ./math.nix {inherit lib;}, }: let hexToDecMap = { "0" = 0; "1" = 1; "2" = 2; "3" = 3; "4" = 4; "5" = 5; "6" = 6; "7" = 7; "8" = 8; "9" = 9; "a" = 10; "b" = 11; "c" = 12; "d" = 13; "e" = 14; "f" = 15; }; base16To10 = exponent: scalar: scalar * math.pow 16 exponent; /* Converts a hexadecimal character to decimal. Only takes a string of length 1. Type: hexCharToDec :: string -> int Args: hex: A hexadecimal character. Example: hexCharToDec "5" => 5 hexCharToDec "e" => 14 hexCharToDec "A" => 10 */ hexCharToDec = hex: let inherit (lib) toLower; lowerHex = toLower hex; in if builtins.stringLength hex != 1 then throw "Function only accepts a single character." else if hexToDecMap ? ${lowerHex} then hexToDecMap."${lowerHex}" else throw "Character ${hex} is not a hexadecimal value."; in rec { /* Converts from hexadecimal to decimal. Type: hexToDec :: string -> int Args: hex: A hexadecimal string. Example: hexadecimal "12" => 18 hexadecimal "FF" => 255 hexadecimal "abcdef" => 11259375 */ hexToDec = hex: let inherit (lib) stringToCharacters reverseList imap0 foldl; decimals = builtins.map hexCharToDec (stringToCharacters hex); decimalsAscending = reverseList decimals; decimalsPowered = imap0 base16To10 decimalsAscending; in foldl builtins.add 0 decimalsPowered; hexToIP = inputString: let len = builtins.stringLength inputString; oct1 = builtins.substring (len - 4) 2 inputString; oct2 = builtins.substring (len - 2) 2 inputString; oct1_dec = builtins.toString (hexToDec oct1); oct2_dec = builtins.toString (hexToDec oct2); in "${oct1_dec}.${oct2_dec}"; hostnameToIP = inputString: let sha256Hash = builtins.hashString "sha256" inputString; in hexToIP sha256Hash; }