about summary refs log tree commit diff
path: root/users/sterni/nix/string/default.nix
diff options
context:
space:
mode:
Diffstat (limited to 'users/sterni/nix/string/default.nix')
-rw-r--r--users/sterni/nix/string/default.nix38
1 files changed, 38 insertions, 0 deletions
diff --git a/users/sterni/nix/string/default.nix b/users/sterni/nix/string/default.nix
index 3fe7c04618c3..19d2cec243c0 100644
--- a/users/sterni/nix/string/default.nix
+++ b/users/sterni/nix/string/default.nix
@@ -59,6 +59,43 @@ let
   # pattern matching for strings only
   match = val: matcher: matcher."${val}";
 
+  /* Bare-bones printf implementation. Supported format specifiers:
+
+     * `%%` escapes `%`
+     * `%s` is substituted by a string
+
+     As expected, the first argument is a format string and the values
+     for its format specifiers need to provided as the next arguments
+     in order.
+
+     Type: string -> (printfVal : either string (a -> printfVal))
+  */
+  printf = formatString:
+    let
+      specifierWithArg = token: builtins.elem token [
+        "%s"
+      ];
+      isSpecifier = lib.hasPrefix "%";
+
+      tokens = lib.flatten (builtins.split "(%.)" formatString);
+      argsNeeded = builtins.length (builtins.filter specifierWithArg tokens);
+
+      format = args: (builtins.foldl' ({ out ? "", argIndex ? 0 }: token: {
+        argIndex = argIndex + (if specifierWithArg token then 1 else 0);
+        out =
+          /**/ if token == "%s" then out + builtins.elemAt args argIndex
+          else if token == "%%" then out + "%"
+          else if isSpecifier token then throw "Unsupported format specifier ${token}"
+          else out + token;
+      }) {} tokens).out;
+
+      accumulateArgs = argCount: args:
+        if argCount > 0
+        then arg: accumulateArgs (argCount - 1) (args ++ [ arg ])
+        else format args;
+    in
+      accumulateArgs argsNeeded [];
+
 in {
   inherit
     take
@@ -72,5 +109,6 @@ in {
     pad
     fit
     match
+    printf
     ;
 }