summary refs log tree commit diff
path: root/pkgs/lib/strings.nix
diff options
context:
space:
mode:
authorNicolas Pierron <nicolas.b.pierron@gmail.com>2009-10-06 09:21:52 +0000
committerNicolas Pierron <nicolas.b.pierron@gmail.com>2009-10-06 09:21:52 +0000
commit915fa6a08f31f44cf4289f785001e7e7b209ee6e (patch)
tree53dcf6635eea77873ea8051a38917b012a11c26b /pkgs/lib/strings.nix
parentbbb4ce1dd77d7a4b056d2ee3c5029c883cf28070 (diff)
downloadnixpkgs-915fa6a08f31f44cf4289f785001e7e7b209ee6e.tar
nixpkgs-915fa6a08f31f44cf4289f785001e7e7b209ee6e.tar.gz
nixpkgs-915fa6a08f31f44cf4289f785001e7e7b209ee6e.tar.bz2
nixpkgs-915fa6a08f31f44cf4289f785001e7e7b209ee6e.tar.lz
nixpkgs-915fa6a08f31f44cf4289f785001e7e7b209ee6e.tar.xz
nixpkgs-915fa6a08f31f44cf4289f785001e7e7b209ee6e.tar.zst
nixpkgs-915fa6a08f31f44cf4289f785001e7e7b209ee6e.zip
introduce the stringAsChars ans replaceChars functions.
svn path=/nixpkgs/trunk/; revision=17670
Diffstat (limited to 'pkgs/lib/strings.nix')
-rw-r--r--pkgs/lib/strings.nix23
1 files changed, 22 insertions, 1 deletions
diff --git a/pkgs/lib/strings.nix b/pkgs/lib/strings.nix
index dc1dbfd8de1..64abb514fb2 100644
--- a/pkgs/lib/strings.nix
+++ b/pkgs/lib/strings.nix
@@ -70,15 +70,36 @@ rec {
     else [(substring 0 1 s)] ++ stringToCharacters (substring 1 (builtins.sub l 1) s);
 
     
+  # Manipulate a string charcater by character and replace them by strings
+  # before concatenating the results.
+  stringAsChars = f: s:
+    concatStrings (
+      map f (stringToCharacters s)
+    );
+
   # same as vim escape function.
   # Each character contained in list is prefixed by "\"
   escape = list : string :
-    lib.concatStrings (map (c: if lib.elem c list then "\\${c}" else c) (stringToCharacters string));
+    stringAsChars (c: if lib.elem c list then "\\${c}" else c) string;
 
   # still ugly slow. But more correct now
   # [] for zsh
   escapeShellArg = lib.escape (stringToCharacters "\\ ';$`()|<>\t*[]");
 
+  # replace characters by their substitutes.  This function is equivalent to
+  # the `tr' command except that one character can be replace by multiple
+  # ones.  e.g.,
+  # replaceChars ["<" ">"] ["&lt;" "&gt;"] "<foo>" returns "&lt;foo&gt;".
+  replaceChars = del: new: s:
+    let
+      subst = c:
+        (lib.fold
+          (sub: res: if sub.fst == c then sub else res)
+          {fst = c; snd = c;} (lib.zipLists del new)
+        ).snd;
+    in
+      stringAsChars subst s;
+
   # Compares strings not requiring context equality
   # Obviously, a workaround but works on all Nix versions
   eqStrings = a: b: (a+(substring 0 0 b)) == ((substring 0 0 a)+b);