Skip to content

Commit

Permalink
Merge pull request NixOS#1912 from dezgeg/replacestrings-take-2
Browse files Browse the repository at this point in the history
libexpr: Fix prim_replaceStrings() to work on an empty source string, take 2
  • Loading branch information
edolstra authored Feb 27, 2018
2 parents 24ec750 + 77e9e1e commit 8a5da93
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
17 changes: 14 additions & 3 deletions src/libexpr/primops.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1913,21 +1913,32 @@ static void prim_replaceStrings(EvalState & state, const Pos & pos, Value * * ar
auto s = state.forceString(*args[2], context, pos);

string res;
for (size_t p = 0; p < s.size(); ) {
// Loops one past last character to handle the case where 'from' contains an empty string.
for (size_t p = 0; p <= s.size(); ) {
bool found = false;
auto i = from.begin();
auto j = to.begin();
for (; i != from.end(); ++i, ++j)
if (s.compare(p, i->size(), *i) == 0) {
found = true;
p += i->size();
res += j->first;
if (i->empty()) {
if (p < s.size())
res += s[p];
p++;
} else {
p += i->size();
}
for (auto& path : j->second)
context.insert(path);
j->second.clear();
break;
}
if (!found) res += s[p++];
if (!found) {
if (p < s.size())
res += s[p];
p++;
}
}

mkString(v, res, context);
Expand Down
2 changes: 1 addition & 1 deletion tests/lang/eval-okay-replacestrings.exp
Original file line number Diff line number Diff line change
@@ -1 +1 @@
[ "faabar" "fbar" "fubar" "faboor" "fubar" ]
[ "faabar" "fbar" "fubar" "faboor" "fubar" "XaXbXcX" "X" "a_b" ]
3 changes: 3 additions & 0 deletions tests/lang/eval-okay-replacestrings.nix
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,7 @@ with builtins;
(replaceStrings ["oo"] ["u"] "foobar")
(replaceStrings ["oo" "a"] ["a" "oo"] "foobar")
(replaceStrings ["oo" "oo"] ["u" "i"] "foobar")
(replaceStrings [""] ["X"] "abc")
(replaceStrings [""] ["X"] "")
(replaceStrings ["-"] ["_"] "a-b")
]

0 comments on commit 8a5da93

Please sign in to comment.