Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix infinite recursion in ReplacedString when <old> string is empty #5523

Merged
merged 2 commits into from
Oct 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 14 additions & 11 deletions lib/init.g
Original file line number Diff line number Diff line change
Expand Up @@ -102,29 +102,32 @@
##
## This cannot be inside "kernel.g" because it is needed to read "kernel.g".
##
ReplacedString := function ( arg )
local str, substr, lss, subs, all, p, s, pp;
str := arg[1];
substr := arg[2];
lss := LEN_LIST( substr );
subs := arg[3];
if LEN_LIST( arg ) > 3 then
all := arg[4] = "all";
ReplacedString := function ( str, old, new, arg... )
local lss, all, p, s, pp;
if old = new then
return str;
fi;
lss := LEN_LIST( old );
if lss = 0 then
Error("<old> must not be empty");
fi;
if LEN_LIST( arg ) > 0 then
all := arg[1] = "all";

Check warning on line 115 in lib/init.g

View check run for this annotation

Codecov / codecov/patch

lib/init.g#L115

Added line #L115 was not covered by tests
else
all := true;
fi;
p := POSITION_SUBSTRING( str, substr, 0 );
p := POSITION_SUBSTRING( str, old, 0 );
if p = fail then
return str;
fi;
s := str{[ ]};
pp := 0;
while p <> fail do
APPEND_LIST_INTR( s, str{[ pp+1 .. p - 1 ]} );
APPEND_LIST_INTR( s, subs );
APPEND_LIST_INTR( s, new );
pp := p + lss - 1;
if all then
p := POSITION_SUBSTRING( str, substr, pp );
p := POSITION_SUBSTRING( str, old, pp );
else
p := fail;
fi;
Expand Down
8 changes: 8 additions & 0 deletions tst/testinstall/strings.tst
Original file line number Diff line number Diff line change
Expand Up @@ -209,5 +209,13 @@ gap> for len in [10,100,1000,10000,100000] do
> Assert(0, Concatenation(str,"\n") = DisplayString(str));
> od;;

#
gap> ReplacedString("Hello world", "Hello", "Goodbye");
"Goodbye world"
gap> ReplacedString("Hello world", "", "");
"Hello world"
gap> ReplacedString("Hello world", "", "*");
Error, <old> must not be empty

#
gap> STOP_TEST( "strings.tst", 1);