Skip to content

[NFC][ADT] Add reverse iterators and value_type to StringRef #105579

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 1 commit into from
Aug 22, 2024
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
12 changes: 12 additions & 0 deletions llvm/include/llvm/ADT/StringRef.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include <cassert>
#include <cstddef>
#include <cstring>
#include <iterator>
#include <limits>
#include <string>
#include <string_view>
Expand Down Expand Up @@ -54,6 +55,9 @@ namespace llvm {
using iterator = const char *;
using const_iterator = const char *;
using size_type = size_t;
using value_type = char;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;

private:
/// The start of the string, in an external buffer.
Expand Down Expand Up @@ -112,6 +116,14 @@ namespace llvm {

iterator end() const { return Data + Length; }

reverse_iterator rbegin() const {
return std::make_reverse_iterator(end());
}

reverse_iterator rend() const {
return std::make_reverse_iterator(begin());
}

const unsigned char *bytes_begin() const {
return reinterpret_cast<const unsigned char *>(begin());
}
Expand Down
14 changes: 11 additions & 3 deletions llvm/unittests/ADT/StringRefTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,17 @@ TEST(StringRefTest, EmptyInitializerList) {

TEST(StringRefTest, Iteration) {
StringRef S("hello");
const char *p = "hello";
for (const char *it = S.begin(), *ie = S.end(); it != ie; ++it, ++p)
EXPECT_EQ(*it, *p);
constexpr StringLiteral CS("hello");

// Note: Cannot use literal strings in equal() as iteration over a literal
// string includes the null terminator.
const std::string_view RefFwd("hello");
const std::string_view RefRev("olleh");

EXPECT_TRUE(equal(S, RefFwd));
EXPECT_TRUE(equal(CS, RefFwd));
EXPECT_TRUE(equal(make_range(S.rbegin(), S.rend()), RefRev));
EXPECT_TRUE(equal(make_range(CS.rbegin(), CS.rend()), RefRev));
}

TEST(StringRefTest, StringOps) {
Expand Down
Loading