aboutsummaryrefslogtreecommitdiff
path: root/lib/strings.nix
diff options
context:
space:
mode:
authorEtienne Laurin <etienne@atnnn.com>2020-10-18 10:15:40 +0000
committerEtienne Laurin <etienne@atnnn.com>2020-10-18 13:19:50 +0000
commitd7464ab4bbb83694587bb2e217c032e0a6c0fd98 (patch)
tree3e9a465746980e46b3d1b7351b247a10152783b8 /lib/strings.nix
parentfa0df4d5aba254e57a4ad86927f4c58f4ca895da (diff)
lib.splitString: use builtin.split
Diffstat (limited to 'lib/strings.nix')
-rw-r--r--lib/strings.nix35
1 files changed, 14 insertions, 21 deletions
diff --git a/lib/strings.nix b/lib/strings.nix
index 9fa9f023561e..d81e46a17631 100644
--- a/lib/strings.nix
+++ b/lib/strings.nix
@@ -315,6 +315,16 @@ rec {
*/
escapeNixString = s: escape ["$"] (builtins.toJSON s);
+ /* Turn a string into an exact regular expression
+
+ Type: string -> string
+
+ Example:
+ escapeRegex "[^a-z]*"
+ => "\\[\\^a-z]\\*"
+ */
+ escapeRegex = escape (stringToCharacters "\\[{()^$?*+|.");
+
/* Quotes a string if it can't be used as an identifier directly.
Type: string -> string
@@ -386,8 +396,6 @@ rec {
/* Cut a string with a separator and produces a list of strings which
were separated by this separator.
- NOTE: this function is not performant and should never be used.
-
Example:
splitString "." "foo.bar.baz"
=> [ "foo" "bar" "baz" ]
@@ -396,26 +404,11 @@ rec {
*/
splitString = _sep: _s:
let
- sep = addContextFrom _s _sep;
- s = addContextFrom _sep _s;
- sepLen = stringLength sep;
- sLen = stringLength s;
- lastSearch = sLen - sepLen;
- startWithSep = startAt:
- substring startAt sepLen s == sep;
-
- recurse = index: startAt:
- let cutUntil = i: [(substring startAt (i - startAt) s)]; in
- if index <= lastSearch then
- if startWithSep index then
- let restartAt = index + sepLen; in
- cutUntil index ++ recurse restartAt restartAt
- else
- recurse (index + 1) startAt
- else
- cutUntil sLen;
+ sep = builtins.unsafeDiscardStringContext _sep;
+ s = builtins.unsafeDiscardStringContext _s;
+ splits = builtins.filter builtins.isString (builtins.split (escapeRegex sep) s);
in
- recurse 0 0;
+ map (v: addContextFrom _sep (addContextFrom _s v)) splits;
/* Return a string without the specified prefix, if the prefix matches.