Skip to content

[flang-rt] Simplify INDEX with len-1 SUBSTRING. #137889

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

Merged
merged 3 commits into from
Apr 30, 2025
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
19 changes: 19 additions & 0 deletions flang-rt/lib/runtime/character.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#include "flang/Common/uint128.h"
#include "flang/Runtime/character.h"
#include "flang/Runtime/cpp-type.h"
#include "flang/Runtime/freestanding-tools.h"
#include <algorithm>
#include <cstring>

Expand Down Expand Up @@ -293,6 +294,24 @@ inline RT_API_ATTRS std::size_t Index(const CHAR *x, std::size_t xLen,
}
return 0;
}
if (wantLen == 1) {
// Trivial case for single character lookup.
// We can use simple forward search.
CHAR ch{want[0]};
if constexpr (std::is_same_v<CHAR, char>) {
if (auto pos{reinterpret_cast<const CHAR *>(
Fortran::runtime::memchr(x, ch, xLen))}) {
return pos - x + 1;
}
} else {
for (std::size_t at{0}; at < xLen; ++at) {
if (x[at] == ch) {
return at + 1;
}
}
}
return 0;
}
// Non-trivial forward substring search: use a simplified form of
// Boyer-Moore substring searching.
for (std::size_t at{1}; at + wantLen - 1 <= xLen;) {
Expand Down
1 change: 1 addition & 0 deletions flang-rt/unittests/Runtime/CharacterTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ TYPED_TEST(SearchTests, IndexTests) {
{"", "a", true, 0},
{"aa", "a", false, 1},
{"aa", "a", true, 2},
{"aAA", "A", false, 2},
{"Fortran that I ran", "that I ran", false, 9},
{"Fortran that I ran", "that I ran", true, 9},
{"Fortran that you ran", "that I ran", false, 0},
Expand Down
Loading