mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-25 00:50:22 +00:00
AK+Tests: Correct off-by-one error when right-trimming text
If the entire string you want to right-trim consists of characters you want to remove, we previously would incorrectly leave the first character there. For example: `trim("aaaaa", "a")` would return "a" instead of "". We can't use `i >= 0` in the loop since that would fail to detect underflow, so instead we keep `i` in the range `size .. 1` and then subtract 1 from it when reading the character. Added some trim() tests while I was at it. (And to confirm that this was the issue.)
This commit is contained in:
parent
8202beeb2b
commit
a0d44026fc
Notes:
sideshowbarker
2024-07-17 06:02:48 +09:00
Author: https://github.com/AtkinsSJ Commit: https://github.com/SerenityOS/serenity/commit/a0d44026fc Pull-request: https://github.com/SerenityOS/serenity/pull/15543
2 changed files with 13 additions and 2 deletions
|
@ -338,10 +338,10 @@ StringView trim(StringView str, StringView characters, TrimMode mode)
|
|||
}
|
||||
|
||||
if (mode == TrimMode::Right || mode == TrimMode::Both) {
|
||||
for (size_t i = str.length() - 1; i > 0; --i) {
|
||||
for (size_t i = str.length(); i > 0; --i) {
|
||||
if (substring_length == 0)
|
||||
return ""sv;
|
||||
if (!characters.contains(str[i]))
|
||||
if (!characters.contains(str[i - 1]))
|
||||
break;
|
||||
--substring_length;
|
||||
}
|
||||
|
|
|
@ -338,6 +338,17 @@ TEST_CASE(is_whitespace)
|
|||
EXPECT(!AK::StringUtils::is_whitespace("a\t"sv));
|
||||
}
|
||||
|
||||
TEST_CASE(trim)
|
||||
{
|
||||
EXPECT_EQ(AK::StringUtils::trim("aaa.a."sv, "."sv, TrimMode::Right), "aaa.a"sv);
|
||||
EXPECT_EQ(AK::StringUtils::trim("...aaa"sv, "."sv, TrimMode::Left), "aaa"sv);
|
||||
EXPECT_EQ(AK::StringUtils::trim("...aaa.a..."sv, "."sv, TrimMode::Both), "aaa.a"sv);
|
||||
EXPECT_EQ(AK::StringUtils::trim("."sv, "."sv, TrimMode::Right), ""sv);
|
||||
EXPECT_EQ(AK::StringUtils::trim("."sv, "."sv, TrimMode::Left), ""sv);
|
||||
EXPECT_EQ(AK::StringUtils::trim("."sv, "."sv, TrimMode::Both), ""sv);
|
||||
EXPECT_EQ(AK::StringUtils::trim("..."sv, "."sv, TrimMode::Both), ""sv);
|
||||
}
|
||||
|
||||
TEST_CASE(find)
|
||||
{
|
||||
String test_string = "1234567";
|
||||
|
|
Loading…
Reference in a new issue