Skip to content

Instantly share code, notes, and snippets.

@sternenseemann
Last active February 19, 2021 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sternenseemann/ddda91bbcdd9019816194df0ab100b6c to your computer and use it in GitHub Desktop.
Save sternenseemann/ddda91bbcdd9019816194df0ab100b6c to your computer and use it in GitHub Desktop.
ord and chr for nix 🤠
{ lib ? (import <nixpkgs> {}).lib }:
let
# ord-data.nix is an auto generated nix file
# which contains single byte strings from
# 0x01 to 0xff in a list where there index
# is equal to their byte-value.
#
# The string at index 0 is empty because nix
# apparently thinks a NUL byte is EOF.
ordData = import ./gen/ord-data.nix;
inherit (lib)
stringToCharacters
concatMapStrings
;
inherit (builtins)
map
elemAt
;
elemIndex = e: l:
let
tailCall = e: l: i:
if l == []
then -1
else if builtins.head l == e
then i
else tailCall e (builtins.tail l) (i + 1);
in tailCall e l 0;
ord = char:
let
i = elemIndex char ordData;
in if i == -1 then 0 else i; # can't have a NUL byte in a string apparently
chr = i:
if i < 1 || i > 255
then throw "chr: only 0x01-0xff is supported"
else elemAt ordData i;
stringToIntegers = str:
map ord (stringToCharacters str);
integersToString = is: concatMapStrings chr is;
in
{
inherit
ord
chr
stringToIntegers
integersToString
;
}
[
""
""
""
""
""
""
""
""
""
"\t"
"\n"
" "
" "
"\r"
""
""
""
""
""
""
""
""
""
""
""
""
""
""
""
""
""
""
" "
"!"
"\""
"#"
"$"
"%"
"&"
"'"
"("
")"
"*"
"+"
","
"-"
"."
"/"
"0"
"1"
"2"
"3"
"4"
"5"
"6"
"7"
"8"
"9"
":"
";"
"<"
"="
">"
"?"
"@"
"A"
"B"
"C"
"D"
"E"
"F"
"G"
"H"
"I"
"J"
"K"
"L"
"M"
"N"
"O"
"P"
"Q"
"R"
"S"
"T"
"U"
"V"
"W"
"X"
"Y"
"Z"
"["
"\\"
"]"
"^"
"_"
"`"
"a"
"b"
"c"
"d"
"e"
"f"
"g"
"h"
"i"
"j"
"k"
"l"
"m"
"n"
"o"
"p"
"q"
"r"
"s"
"t"
"u"
"v"
"w"
"x"
"y"
"z"
"{"
"|"
"}"
"~"
""
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
"�"
]
#include <stdio.h>
int main(void) {
fputs("[\n \"\"\n", stdout);
for(int i = 1; i <= 0xff; i++) {
for(int j = 0; j < 2; j++)
putchar(' ');
putchar('\"');
switch(i) {
case '\n':
fputs("\\n", stdout);
break;
case '\t':
fputs("\\t", stdout);
break;
case '\\':
fputs("\\\\", stdout);
break;
case '\"':
fputs("\\\"", stdout);
break;
case '\r':
fputs("\\r", stdout);
break;
default:
putchar(i);
}
putchar('\"');
putchar('\n');
}
fputs("]\n", stdout);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment