about summary refs log tree commit diff
path: root/users/Profpatsch/netencode/gen.nix
diff options
context:
space:
mode:
authorProfpatsch <mail@profpatsch.de>2021-01-26T13·09+0100
committerProfpatsch <mail@profpatsch.de>2021-01-27T13·41+0000
commitf68781da1be5489892b566b050308916b4f58424 (patch)
tree85c5d0c8ea7867335487f58bb35086014d690078 /users/Profpatsch/netencode/gen.nix
parentb725e9b7e4682d7edea29d7f5ab4e9b82043f776 (diff)
chore(users/Profpatsch/netencode): netencode.nix -> gen.nix r/2149
Change-Id: I7ccbfe863fbff65015caa8c740b80c4bb5c59dc1
Reviewed-on: https://cl.tvl.fyi/c/depot/+/2446
Reviewed-by: Profpatsch <mail@profpatsch.de>
Tested-by: BuildkiteCI
Diffstat (limited to 'users/Profpatsch/netencode/gen.nix')
-rw-r--r--users/Profpatsch/netencode/gen.nix65
1 files changed, 65 insertions, 0 deletions
diff --git a/users/Profpatsch/netencode/gen.nix b/users/Profpatsch/netencode/gen.nix
new file mode 100644
index 0000000000..5f98f27f67
--- /dev/null
+++ b/users/Profpatsch/netencode/gen.nix
@@ -0,0 +1,65 @@
+{ lib }:
+let
+
+  netstring = tag: suffix: s:
+    "${tag}${toString (builtins.stringLength s)}:${s}${suffix}";
+
+  unit = "u,";
+
+  n1 = b: if b then "n1:1," else "n1:0,";
+
+  n = i: n: netstring "n${toString i}" "," (toString n);
+  i = i: n: netstring "i${toString i}" "," (toString n);
+
+  n3 = n 3;
+  n6 = n 6;
+  n7 = n 7;
+
+  i3 = i 3;
+  i6 = i 6;
+  i7 = i 7;
+
+  text = netstring "t" ",";
+  binary = netstring "b" ",";
+
+  tag = key: val: netstring "<" "|" key + val;
+
+  concatStrings = builtins.concatStringsSep "";
+
+  record = lokv: netstring "{" "}"
+    (concatStrings (map ({key, val}: tag key val) lokv));
+
+  list = l: netstring "[" "]" (concatStrings l);
+
+  dwim = val:
+    let match = {
+      "bool" = n1;
+      "int" = i6;
+      "string" = text;
+      "set" = attrs: record (lib.mapAttrsToList
+        (k: v: {
+          key = k;
+          val = dwim v;
+        }) attrs);
+      "list" = l: list (map dwim l);
+    };
+    in match.${builtins.typeOf val} val;
+
+in {
+  inherit
+    unit
+    n1
+    n3
+    n6
+    n7
+    i3
+    i6
+    i7
+    text
+    binary
+    tag
+    record
+    list
+    dwim
+    ;
+}