Zachary Turner | fac2da1 | 2018-07-16 21:24:03 +0000 | [diff] [blame^] | 1 | //===--- StringView.h -------------------------------------------*- C++ -*-===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | // |
| 9 | // This file contains a limited version of LLVM's StringView class. It is |
| 10 | // copied here so that LLVMDemangle need not take a dependency on LLVMSupport. |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #ifndef LLVM_DEMANGLE_STRINGVIEW_H |
| 14 | #define LLVM_DEMANGLE_STRINGVIEW_H |
| 15 | |
| 16 | #include <algorithm> |
| 17 | |
| 18 | class StringView { |
| 19 | const char *First; |
| 20 | const char *Last; |
| 21 | |
| 22 | public: |
| 23 | template <size_t N> |
| 24 | StringView(const char (&Str)[N]) : First(Str), Last(Str + N - 1) {} |
| 25 | StringView(const char *First_, const char *Last_) |
| 26 | : First(First_), Last(Last_) {} |
| 27 | StringView() : First(nullptr), Last(nullptr) {} |
| 28 | |
| 29 | StringView substr(size_t From, size_t To) { |
| 30 | if (To >= size()) |
| 31 | To = size() - 1; |
| 32 | if (From >= size()) |
| 33 | From = size() - 1; |
| 34 | return StringView(First + From, First + To); |
| 35 | } |
| 36 | |
| 37 | StringView dropFront(size_t N) const { |
| 38 | if (N >= size()) |
| 39 | N = size() - 1; |
| 40 | return StringView(First + N, Last); |
| 41 | } |
| 42 | |
| 43 | bool startsWith(StringView Str) const { |
| 44 | if (Str.size() > size()) |
| 45 | return false; |
| 46 | return std::equal(Str.begin(), Str.end(), begin()); |
| 47 | } |
| 48 | |
| 49 | const char &operator[](size_t Idx) const { return *(begin() + Idx); } |
| 50 | |
| 51 | const char *begin() const { return First; } |
| 52 | const char *end() const { return Last; } |
| 53 | size_t size() const { return static_cast<size_t>(Last - First); } |
| 54 | bool empty() const { return First == Last; } |
| 55 | }; |
| 56 | |
| 57 | inline bool operator==(const StringView &LHS, const StringView &RHS) { |
| 58 | return LHS.size() == RHS.size() && |
| 59 | std::equal(LHS.begin(), LHS.end(), RHS.begin()); |
| 60 | } |
| 61 | |
| 62 | #endif |