[llvm] [NFC][ADT] Add reverse iterators and `value_type` to StringRef (PR #105579)
Rahul Joshi via llvm-commits
llvm-commits at lists.llvm.org
Thu Aug 22 05:26:08 PDT 2024
https://github.com/jurahul updated https://github.com/llvm/llvm-project/pull/105579
>From 035b3ea58e2bf4b5ca26933deb482952d268e988 Mon Sep 17 00:00:00 2001
From: Rahul Joshi <rjoshi at nvidia.com>
Date: Wed, 21 Aug 2024 03:51:58 -0700
Subject: [PATCH] [NFC][ADT] Add reverse iterators and `value_type` to
StringRef
- Add reverse iterators and `value_type` to StringRef.
- Add unit test for all 4 iterator flavors.
- This prepares StringRef to be used with `SequenceToOffsetTable`.
---
llvm/include/llvm/ADT/StringRef.h | 12 ++++++++++++
llvm/unittests/ADT/StringRefTest.cpp | 14 +++++++++++---
2 files changed, 23 insertions(+), 3 deletions(-)
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 a0529b03ae8c22..ec9cdc197597d0 100644
--- a/llvm/unittests/ADT/StringRefTest.cpp
+++ b/llvm/unittests/ADT/StringRefTest.cpp
@@ -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) {
More information about the llvm-commits
mailing list