Skip to content

Commit

Permalink
[NFC][ADT] Add reverse iterators and value_type to StringRef (llvm#…
Browse files Browse the repository at this point in the history
…105579)

- Add reverse iterators and `value_type` to StringRef.
- Add unit test for all 4 iterator flavors.
- This prepares StringRef to be used with `SequenceToOffsetTable`.
  • Loading branch information
jurahul authored and cjdb committed Aug 23, 2024
1 parent 89187e9 commit dde207d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
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

0 comments on commit dde207d

Please sign in to comment.