Added Find Sequence to Spans

Added FindSequence to Span.h

Refactored String find to use Span::Find_Seq in Ustring.cpp
This commit is contained in:
Colin O'Rourke 2025-03-18 13:09:17 -07:00
parent 6efa557e9b
commit 03d32c68a9
4 changed files with 122 additions and 168 deletions

View file

@ -98,8 +98,11 @@ public:
// Algorithms.
constexpr int64_t find(const T &p_val, uint64_t p_from = 0) const;
constexpr int64_t find_sequence(const Span<T> &p_span, uint64_t p_from = 0) const;
constexpr int64_t rfind(const T &p_val, uint64_t p_from) const;
_FORCE_INLINE_ constexpr int64_t rfind(const T &p_val) const { return rfind(p_val, size() - 1); }
constexpr int64_t rfind_sequence(const Span<T> &p_span, uint64_t p_from) const;
_FORCE_INLINE_ constexpr int64_t rfind_sequence(const Span<T> &p_span) const { return rfind_sequence(p_span, size() - p_span.size()); }
constexpr uint64_t count(const T &p_val) const;
/// Find the index of the given value using binary search.
/// Note: Assumes that elements in the span are sorted. Otherwise, use find() instead.
@ -117,6 +120,24 @@ constexpr int64_t Span<T>::find(const T &p_val, uint64_t p_from) const {
return -1;
}
template <typename T>
constexpr int64_t Span<T>::find_sequence(const Span<T> &p_span, uint64_t p_from) const {
for (uint64_t i = p_from; i <= size() - p_span.size(); i++) {
bool found = true;
for (uint64_t j = 0; j < p_span.size(); j++) {
if (ptr()[i + j] != p_span.ptr()[j]) {
found = false;
break;
}
}
if (found) {
return i;
}
}
return -1;
}
template <typename T>
constexpr int64_t Span<T>::rfind(const T &p_val, uint64_t p_from) const {
for (int64_t i = p_from; i >= 0; i--) {
@ -127,6 +148,24 @@ constexpr int64_t Span<T>::rfind(const T &p_val, uint64_t p_from) const {
return -1;
}
template <typename T>
constexpr int64_t Span<T>::rfind_sequence(const Span<T> &p_span, uint64_t p_from) const {
for (int64_t i = p_from; i >= 0; i--) {
bool found = true;
for (uint64_t j = 0; j < p_span.size(); j++) {
if (ptr()[i + j] != p_span.ptr()[j]) {
found = false;
break;
}
}
if (found) {
return i;
}
}
return -1;
}
template <typename T>
constexpr uint64_t Span<T>::count(const T &p_val) const {
uint64_t amount = 0;