[llvm] [NFC][ADT] Add reverse iterators and `value_type` to StringRef (PR #105579)

via llvm-commits llvm-commits at lists.llvm.org
Wed Aug 21 15:26:21 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-adt

Author: Rahul Joshi (jurahul)

<details>
<summary>Changes</summary>

- Add reverse iterators and `value_type` to StringRef.
- Add unit test for all 4 iterator flavors.
- This prepares StringRef to be used with `SequenceToOffsetTable`.

---
Full diff: https://github.com/llvm/llvm-project/pull/105579.diff


2 Files Affected:

- (modified) llvm/include/llvm/ADT/StringRef.h (+12) 
- (modified) llvm/unittests/ADT/StringRefTest.cpp (+12-3) 


``````````diff
diff --git a/llvm/include/llvm/ADT/StringRef.h b/llvm/include/llvm/ADT/StringRef.h
index 049f22b03e46e8..952d6485dafc1a 100644
--- a/llvm/include/llvm/ADT/StringRef.h
+++ b/llvm/include/llvm/ADT/StringRef.h
@@ -17,6 +17,7 @@
 #include <cassert>
 #include <cstddef>
 #include <cstring>
+#include <iterator>
 #include <limits>
 #include <string>
 #include <string_view>
@@ -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.
@@ -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());
     }
diff --git a/llvm/unittests/ADT/StringRefTest.cpp b/llvm/unittests/ADT/StringRefTest.cpp
index 40351c99d0185c..0330e1c7ca1960 100644
--- a/llvm/unittests/ADT/StringRefTest.cpp
+++ b/llvm/unittests/ADT/StringRefTest.cpp
@@ -72,9 +72,18 @@ 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.
+  constexpr std::string_view RefFwd("hello");
+  constexpr std::string_view RefRev("olleh");
+
+  EXPECT_TRUE(equal(S, RefFwd));
+  EXPECT_TRUE(equal(CS, RefFwd));
+  // reverse() builds an iterator range using StringRef::rbegin()/rend().
+  EXPECT_TRUE(equal(reverse(S), RefRev));
+  EXPECT_TRUE(equal(reverse(CS), RefRev));
 }
 
 TEST(StringRefTest, StringOps) {

``````````

</details>


https://github.com/llvm/llvm-project/pull/105579


More information about the llvm-commits mailing list