1 //===--- StringView.h -------------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // FIXME: Use std::string_view instead when we support C++17.
11 //===----------------------------------------------------------------------===//
13 #ifndef DEMANGLE_STRINGVIEW_H
14 #define DEMANGLE_STRINGVIEW_H
16 #include "DemangleConfig.h"
21 DEMANGLE_NAMESPACE_BEGIN
28 static const size_t npos
= ~size_t(0);
31 StringView(const char (&Str
)[N
]) : First(Str
), Last(Str
+ N
- 1) {}
32 StringView(const char *First_
, const char *Last_
)
33 : First(First_
), Last(Last_
) {}
34 StringView(const char *First_
, size_t Len
)
35 : First(First_
), Last(First_
+ Len
) {}
36 StringView(const char *Str
) : First(Str
), Last(Str
+ std::strlen(Str
)) {}
37 StringView() : First(nullptr), Last(nullptr) {}
39 StringView
substr(size_t From
) const {
40 return StringView(begin() + From
, size() - From
);
43 size_t find(char C
, size_t From
= 0) const {
44 size_t FindBegin
= std::min(From
, size());
45 // Avoid calling memchr with nullptr.
46 if (FindBegin
< size()) {
47 // Just forward to memchr, which is faster than a hand-rolled loop.
48 if (const void *P
= ::memchr(First
+ FindBegin
, C
, size() - FindBegin
))
49 return size_t(static_cast<const char *>(P
) - First
);
54 StringView
substr(size_t From
, size_t To
) const {
59 return StringView(First
+ From
, First
+ To
);
62 StringView
dropFront(size_t N
= 1) const {
65 return StringView(First
+ N
, Last
);
68 StringView
dropBack(size_t N
= 1) const {
71 return StringView(First
, Last
- N
);
89 bool consumeFront(char C
) {
96 bool consumeFront(StringView S
) {
99 *this = dropFront(S
.size());
103 bool startsWith(char C
) const { return !empty() && *begin() == C
; }
105 bool startsWith(StringView Str
) const {
106 if (Str
.size() > size())
108 return std::equal(Str
.begin(), Str
.end(), begin());
111 const char &operator[](size_t Idx
) const { return *(begin() + Idx
); }
113 const char *begin() const { return First
; }
114 const char *end() const { return Last
; }
115 size_t size() const { return static_cast<size_t>(Last
- First
); }
116 bool empty() const { return First
== Last
; }
119 inline bool operator==(const StringView
&LHS
, const StringView
&RHS
) {
120 return LHS
.size() == RHS
.size() &&
121 std::equal(LHS
.begin(), LHS
.end(), RHS
.begin());
124 DEMANGLE_NAMESPACE_END