Skip to content

Commit dde207d

Browse files
jurahulcjdb
authored andcommitted
[NFC][ADT] Add reverse iterators and value_type to StringRef (llvm#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`.
1 parent 89187e9 commit dde207d

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

llvm/include/llvm/ADT/StringRef.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
#include <cassert>
1818
#include <cstddef>
1919
#include <cstring>
20+
#include <iterator>
2021
#include <limits>
2122
#include <string>
2223
#include <string_view>
@@ -54,6 +55,9 @@ namespace llvm {
5455
using iterator = const char *;
5556
using const_iterator = const char *;
5657
using size_type = size_t;
58+
using value_type = char;
59+
using reverse_iterator = std::reverse_iterator<iterator>;
60+
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
5761

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

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

119+
reverse_iterator rbegin() const {
120+
return std::make_reverse_iterator(end());
121+
}
122+
123+
reverse_iterator rend() const {
124+
return std::make_reverse_iterator(begin());
125+
}
126+
115127
const unsigned char *bytes_begin() const {
116128
return reinterpret_cast<const unsigned char *>(begin());
117129
}

llvm/unittests/ADT/StringRefTest.cpp

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,17 @@ TEST(StringRefTest, EmptyInitializerList) {
5757

5858
TEST(StringRefTest, Iteration) {
5959
StringRef S("hello");
60-
const char *p = "hello";
61-
for (const char *it = S.begin(), *ie = S.end(); it != ie; ++it, ++p)
62-
EXPECT_EQ(*it, *p);
60+
constexpr StringLiteral CS("hello");
61+
62+
// Note: Cannot use literal strings in equal() as iteration over a literal
63+
// string includes the null terminator.
64+
const std::string_view RefFwd("hello");
65+
const std::string_view RefRev("olleh");
66+
67+
EXPECT_TRUE(equal(S, RefFwd));
68+
EXPECT_TRUE(equal(CS, RefFwd));
69+
EXPECT_TRUE(equal(make_range(S.rbegin(), S.rend()), RefRev));
70+
EXPECT_TRUE(equal(make_range(CS.rbegin(), CS.rend()), RefRev));
6371
}
6472

6573
TEST(StringRefTest, StringOps) {

0 commit comments

Comments
 (0)