1 //===- StringRef.h - Constant String Reference Wrapper ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_ADT_STRINGREF_H
11 #define LLVM_ADT_STRINGREF_H
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/iterator_range.h"
15 #include "llvm/Support/Compiler.h"
22 #include <type_traits>
29 template <typename T> class SmallVectorImpl;
32 /// Helper functions for StringRef::getAsInteger.
33 bool getAsUnsignedInteger(StringRef Str, unsigned Radix,
34 unsigned long long &Result);
36 bool getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result);
38 bool consumeUnsignedInteger(StringRef &Str, unsigned Radix,
39 unsigned long long &Result);
40 bool consumeSignedInteger(StringRef &Str, unsigned Radix, long long &Result);
42 /// StringRef - Represent a constant reference to a string, i.e. a character
43 /// array and a length, which need not be null terminated.
45 /// This class does not own the string data, it is expected to be used in
46 /// situations where the character data resides in some other buffer, whose
47 /// lifetime extends past that of the StringRef. For this reason, it is not in
48 /// general safe to store a StringRef.
51 static const size_t npos = ~size_t(0);
53 using iterator = const char *;
54 using const_iterator = const char *;
55 using size_type = size_t;
58 /// The start of the string, in an external buffer.
59 const char *Data = nullptr;
61 /// The length of the string.
64 // Workaround memcmp issue with null pointers (undefined behavior)
65 // by providing a specialized version
66 LLVM_ATTRIBUTE_ALWAYS_INLINE
67 static int compareMemory(const char *Lhs, const char *Rhs, size_t Length) {
68 if (Length == 0) { return 0; }
69 return ::memcmp(Lhs,Rhs,Length);
73 /// @name Constructors
76 /// Construct an empty string ref.
77 /*implicit*/ StringRef() = default;
79 /// Disable conversion from nullptr. This prevents things like
81 StringRef(std::nullptr_t) = delete;
83 /// Construct a string ref from a cstring.
84 LLVM_ATTRIBUTE_ALWAYS_INLINE
85 /*implicit*/ StringRef(const char *Str)
86 : Data(Str), Length(Str ? ::strlen(Str) : 0) {}
88 /// Construct a string ref from a pointer and length.
89 LLVM_ATTRIBUTE_ALWAYS_INLINE
90 /*implicit*/ constexpr StringRef(const char *data, size_t length)
91 : Data(data), Length(length) {}
93 /// Construct a string ref from an std::string.
94 LLVM_ATTRIBUTE_ALWAYS_INLINE
95 /*implicit*/ StringRef(const std::string &Str)
96 : Data(Str.data()), Length(Str.length()) {}
98 static StringRef withNullAsEmpty(const char *data) {
99 return StringRef(data ? data : "");
106 iterator begin() const { return Data; }
108 iterator end() const { return Data + Length; }
110 const unsigned char *bytes_begin() const {
111 return reinterpret_cast<const unsigned char *>(begin());
113 const unsigned char *bytes_end() const {
114 return reinterpret_cast<const unsigned char *>(end());
116 iterator_range<const unsigned char *> bytes() const {
117 return make_range(bytes_begin(), bytes_end());
121 /// @name String Operations
124 /// data - Get a pointer to the start of the string (which may not be null
127 LLVM_ATTRIBUTE_ALWAYS_INLINE
128 const char *data() const { return Data; }
130 /// empty - Check if the string is empty.
132 LLVM_ATTRIBUTE_ALWAYS_INLINE
133 bool empty() const { return Length == 0; }
135 /// size - Get the string size.
137 LLVM_ATTRIBUTE_ALWAYS_INLINE
138 size_t size() const { return Length; }
140 /// front - Get the first character in the string.
147 /// back - Get the last character in the string.
151 return Data[Length-1];
154 // copy - Allocate copy in Allocator and return StringRef to it.
155 template <typename Allocator>
156 LLVM_NODISCARD StringRef copy(Allocator &A) const {
157 // Don't request a length 0 copy from the allocator.
160 char *S = A.template Allocate<char>(Length);
161 std::copy(begin(), end(), S);
162 return StringRef(S, Length);
165 /// equals - Check for string equality, this is more efficient than
166 /// compare() when the relative ordering of inequal strings isn't needed.
168 LLVM_ATTRIBUTE_ALWAYS_INLINE
169 bool equals(StringRef RHS) const {
170 return (Length == RHS.Length &&
171 compareMemory(Data, RHS.Data, RHS.Length) == 0);
174 /// equals_lower - Check for string equality, ignoring case.
176 bool equals_lower(StringRef RHS) const {
177 return Length == RHS.Length && compare_lower(RHS) == 0;
180 /// compare - Compare two strings; the result is -1, 0, or 1 if this string
181 /// is lexicographically less than, equal to, or greater than the \p RHS.
183 LLVM_ATTRIBUTE_ALWAYS_INLINE
184 int compare(StringRef RHS) const {
185 // Check the prefix for a mismatch.
186 if (int Res = compareMemory(Data, RHS.Data, std::min(Length, RHS.Length)))
187 return Res < 0 ? -1 : 1;
189 // Otherwise the prefixes match, so we only need to check the lengths.
190 if (Length == RHS.Length)
192 return Length < RHS.Length ? -1 : 1;
195 /// compare_lower - Compare two strings, ignoring case.
197 int compare_lower(StringRef RHS) const;
199 /// compare_numeric - Compare two strings, treating sequences of digits as
202 int compare_numeric(StringRef RHS) const;
204 /// Determine the edit distance between this string and another
207 /// \param Other the string to compare this string against.
209 /// \param AllowReplacements whether to allow character
210 /// replacements (change one character into another) as a single
211 /// operation, rather than as two operations (an insertion and a
214 /// \param MaxEditDistance If non-zero, the maximum edit distance that
215 /// this routine is allowed to compute. If the edit distance will exceed
216 /// that maximum, returns \c MaxEditDistance+1.
218 /// \returns the minimum number of character insertions, removals,
219 /// or (if \p AllowReplacements is \c true) replacements needed to
220 /// transform one of the given strings into the other. If zero,
221 /// the strings are identical.
223 unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
224 unsigned MaxEditDistance = 0) const;
226 /// str - Get the contents as an std::string.
228 std::string str() const {
229 if (!Data) return std::string();
230 return std::string(Data, Length);
234 /// @name Operator Overloads
238 char operator[](size_t Index) const {
239 assert(Index < Length && "Invalid index!");
243 /// Disallow accidental assignment from a temporary std::string.
245 /// The declaration here is extra complicated so that `stringRef = {}`
246 /// and `stringRef = "abc"` continue to select the move assignment operator.
247 template <typename T>
248 typename std::enable_if<std::is_same<T, std::string>::value,
250 operator=(T &&Str) = delete;
253 /// @name Type Conversions
256 operator std::string() const {
261 /// @name String Predicates
264 /// Check if this string starts with the given \p Prefix.
266 LLVM_ATTRIBUTE_ALWAYS_INLINE
267 bool startswith(StringRef Prefix) const {
268 return Length >= Prefix.Length &&
269 compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
272 /// Check if this string starts with the given \p Prefix, ignoring case.
274 bool startswith_lower(StringRef Prefix) const;
276 /// Check if this string ends with the given \p Suffix.
278 LLVM_ATTRIBUTE_ALWAYS_INLINE
279 bool endswith(StringRef Suffix) const {
280 return Length >= Suffix.Length &&
281 compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
284 /// Check if this string ends with the given \p Suffix, ignoring case.
286 bool endswith_lower(StringRef Suffix) const;
289 /// @name String Searching
292 /// Search for the first character \p C in the string.
294 /// \returns The index of the first occurrence of \p C, or npos if not
297 LLVM_ATTRIBUTE_ALWAYS_INLINE
298 size_t find(char C, size_t From = 0) const {
299 size_t FindBegin = std::min(From, Length);
300 if (FindBegin < Length) { // Avoid calling memchr with nullptr.
301 // Just forward to memchr, which is faster than a hand-rolled loop.
302 if (const void *P = ::memchr(Data + FindBegin, C, Length - FindBegin))
303 return static_cast<const char *>(P) - Data;
308 /// Search for the first character \p C in the string, ignoring case.
310 /// \returns The index of the first occurrence of \p C, or npos if not
313 size_t find_lower(char C, size_t From = 0) const;
315 /// Search for the first character satisfying the predicate \p F
317 /// \returns The index of the first character satisfying \p F starting from
318 /// \p From, or npos if not found.
320 LLVM_ATTRIBUTE_ALWAYS_INLINE
321 size_t find_if(function_ref<bool(char)> F, size_t From = 0) const {
322 StringRef S = drop_front(From);
325 return size() - S.size();
331 /// Search for the first character not satisfying the predicate \p F
333 /// \returns The index of the first character not satisfying \p F starting
334 /// from \p From, or npos if not found.
336 LLVM_ATTRIBUTE_ALWAYS_INLINE
337 size_t find_if_not(function_ref<bool(char)> F, size_t From = 0) const {
338 return find_if([F](char c) { return !F(c); }, From);
341 /// Search for the first string \p Str in the string.
343 /// \returns The index of the first occurrence of \p Str, or npos if not
346 size_t find(StringRef Str, size_t From = 0) const;
348 /// Search for the first string \p Str in the string, ignoring case.
350 /// \returns The index of the first occurrence of \p Str, or npos if not
353 size_t find_lower(StringRef Str, size_t From = 0) const;
355 /// Search for the last character \p C in the string.
357 /// \returns The index of the last occurrence of \p C, or npos if not
360 size_t rfind(char C, size_t From = npos) const {
361 From = std::min(From, Length);
371 /// Search for the last character \p C in the string, ignoring case.
373 /// \returns The index of the last occurrence of \p C, or npos if not
376 size_t rfind_lower(char C, size_t From = npos) const;
378 /// Search for the last string \p Str in the string.
380 /// \returns The index of the last occurrence of \p Str, or npos if not
383 size_t rfind(StringRef Str) const;
385 /// Search for the last string \p Str in the string, ignoring case.
387 /// \returns The index of the last occurrence of \p Str, or npos if not
390 size_t rfind_lower(StringRef Str) const;
392 /// Find the first character in the string that is \p C, or npos if not
393 /// found. Same as find.
395 size_t find_first_of(char C, size_t From = 0) const {
396 return find(C, From);
399 /// Find the first character in the string that is in \p Chars, or npos if
402 /// Complexity: O(size() + Chars.size())
404 size_t find_first_of(StringRef Chars, size_t From = 0) const;
406 /// Find the first character in the string that is not \p C or npos if not
409 size_t find_first_not_of(char C, size_t From = 0) const;
411 /// Find the first character in the string that is not in the string
412 /// \p Chars, or npos if not found.
414 /// Complexity: O(size() + Chars.size())
416 size_t find_first_not_of(StringRef Chars, size_t From = 0) const;
418 /// Find the last character in the string that is \p C, or npos if not
421 size_t find_last_of(char C, size_t From = npos) const {
422 return rfind(C, From);
425 /// Find the last character in the string that is in \p C, or npos if not
428 /// Complexity: O(size() + Chars.size())
430 size_t find_last_of(StringRef Chars, size_t From = npos) const;
432 /// Find the last character in the string that is not \p C, or npos if not
435 size_t find_last_not_of(char C, size_t From = npos) const;
437 /// Find the last character in the string that is not in \p Chars, or
438 /// npos if not found.
440 /// Complexity: O(size() + Chars.size())
442 size_t find_last_not_of(StringRef Chars, size_t From = npos) const;
444 /// Return true if the given string is a substring of *this, and false
447 LLVM_ATTRIBUTE_ALWAYS_INLINE
448 bool contains(StringRef Other) const { return find(Other) != npos; }
450 /// Return true if the given character is contained in *this, and false
453 LLVM_ATTRIBUTE_ALWAYS_INLINE
454 bool contains(char C) const { return find_first_of(C) != npos; }
456 /// Return true if the given string is a substring of *this, and false
459 LLVM_ATTRIBUTE_ALWAYS_INLINE
460 bool contains_lower(StringRef Other) const {
461 return find_lower(Other) != npos;
464 /// Return true if the given character is contained in *this, and false
467 LLVM_ATTRIBUTE_ALWAYS_INLINE
468 bool contains_lower(char C) const { return find_lower(C) != npos; }
471 /// @name Helpful Algorithms
474 /// Return the number of occurrences of \p C in the string.
476 size_t count(char C) const {
478 for (size_t i = 0, e = Length; i != e; ++i)
484 /// Return the number of non-overlapped occurrences of \p Str in
486 size_t count(StringRef Str) const;
488 /// Parse the current string as an integer of the specified radix. If
489 /// \p Radix is specified as zero, this does radix autosensing using
490 /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
492 /// If the string is invalid or if only a subset of the string is valid,
493 /// this returns true to signify the error. The string is considered
494 /// erroneous if empty or if it overflows T.
495 template <typename T>
496 typename std::enable_if<std::numeric_limits<T>::is_signed, bool>::type
497 getAsInteger(unsigned Radix, T &Result) const {
499 if (getAsSignedInteger(*this, Radix, LLVal) ||
500 static_cast<T>(LLVal) != LLVal)
506 template <typename T>
507 typename std::enable_if<!std::numeric_limits<T>::is_signed, bool>::type
508 getAsInteger(unsigned Radix, T &Result) const {
509 unsigned long long ULLVal;
510 // The additional cast to unsigned long long is required to avoid the
511 // Visual C++ warning C4805: '!=' : unsafe mix of type 'bool' and type
512 // 'unsigned __int64' when instantiating getAsInteger with T = bool.
513 if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
514 static_cast<unsigned long long>(static_cast<T>(ULLVal)) != ULLVal)
520 /// Parse the current string as an integer of the specified radix. If
521 /// \p Radix is specified as zero, this does radix autosensing using
522 /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
524 /// If the string does not begin with a number of the specified radix,
525 /// this returns true to signify the error. The string is considered
526 /// erroneous if empty or if it overflows T.
527 /// The portion of the string representing the discovered numeric value
528 /// is removed from the beginning of the string.
529 template <typename T>
530 typename std::enable_if<std::numeric_limits<T>::is_signed, bool>::type
531 consumeInteger(unsigned Radix, T &Result) {
533 if (consumeSignedInteger(*this, Radix, LLVal) ||
534 static_cast<long long>(static_cast<T>(LLVal)) != LLVal)
540 template <typename T>
541 typename std::enable_if<!std::numeric_limits<T>::is_signed, bool>::type
542 consumeInteger(unsigned Radix, T &Result) {
543 unsigned long long ULLVal;
544 if (consumeUnsignedInteger(*this, Radix, ULLVal) ||
545 static_cast<unsigned long long>(static_cast<T>(ULLVal)) != ULLVal)
551 /// Parse the current string as an integer of the specified \p Radix, or of
552 /// an autosensed radix if the \p Radix given is 0. The current value in
553 /// \p Result is discarded, and the storage is changed to be wide enough to
554 /// store the parsed integer.
556 /// \returns true if the string does not solely consist of a valid
557 /// non-empty number in the appropriate base.
559 /// APInt::fromString is superficially similar but assumes the
560 /// string is well-formed in the given radix.
561 bool getAsInteger(unsigned Radix, APInt &Result) const;
563 /// Parse the current string as an IEEE double-precision floating
564 /// point value. The string must be a well-formed double.
566 /// If \p AllowInexact is false, the function will fail if the string
567 /// cannot be represented exactly. Otherwise, the function only fails
568 /// in case of an overflow or underflow.
569 bool getAsDouble(double &Result, bool AllowInexact = true) const;
572 /// @name String Operations
575 // Convert the given ASCII string to lowercase.
577 std::string lower() const;
579 /// Convert the given ASCII string to uppercase.
581 std::string upper() const;
584 /// @name Substring Operations
587 /// Return a reference to the substring from [Start, Start + N).
589 /// \param Start The index of the starting character in the substring; if
590 /// the index is npos or greater than the length of the string then the
591 /// empty substring will be returned.
593 /// \param N The number of characters to included in the substring. If N
594 /// exceeds the number of characters remaining in the string, the string
595 /// suffix (starting with \p Start) will be returned.
597 LLVM_ATTRIBUTE_ALWAYS_INLINE
598 StringRef substr(size_t Start, size_t N = npos) const {
599 Start = std::min(Start, Length);
600 return StringRef(Data + Start, std::min(N, Length - Start));
603 /// Return a StringRef equal to 'this' but with only the first \p N
604 /// elements remaining. If \p N is greater than the length of the
605 /// string, the entire string is returned.
607 LLVM_ATTRIBUTE_ALWAYS_INLINE
608 StringRef take_front(size_t N = 1) const {
611 return drop_back(size() - N);
614 /// Return a StringRef equal to 'this' but with only the last \p N
615 /// elements remaining. If \p N is greater than the length of the
616 /// string, the entire string is returned.
618 LLVM_ATTRIBUTE_ALWAYS_INLINE
619 StringRef take_back(size_t N = 1) const {
622 return drop_front(size() - N);
625 /// Return the longest prefix of 'this' such that every character
626 /// in the prefix satisfies the given predicate.
628 LLVM_ATTRIBUTE_ALWAYS_INLINE
629 StringRef take_while(function_ref<bool(char)> F) const {
630 return substr(0, find_if_not(F));
633 /// Return the longest prefix of 'this' such that no character in
634 /// the prefix satisfies the given predicate.
636 LLVM_ATTRIBUTE_ALWAYS_INLINE
637 StringRef take_until(function_ref<bool(char)> F) const {
638 return substr(0, find_if(F));
641 /// Return a StringRef equal to 'this' but with the first \p N elements
644 LLVM_ATTRIBUTE_ALWAYS_INLINE
645 StringRef drop_front(size_t N = 1) const {
646 assert(size() >= N && "Dropping more elements than exist");
650 /// Return a StringRef equal to 'this' but with the last \p N elements
653 LLVM_ATTRIBUTE_ALWAYS_INLINE
654 StringRef drop_back(size_t N = 1) const {
655 assert(size() >= N && "Dropping more elements than exist");
656 return substr(0, size()-N);
659 /// Return a StringRef equal to 'this', but with all characters satisfying
660 /// the given predicate dropped from the beginning of the string.
662 LLVM_ATTRIBUTE_ALWAYS_INLINE
663 StringRef drop_while(function_ref<bool(char)> F) const {
664 return substr(find_if_not(F));
667 /// Return a StringRef equal to 'this', but with all characters not
668 /// satisfying the given predicate dropped from the beginning of the string.
670 LLVM_ATTRIBUTE_ALWAYS_INLINE
671 StringRef drop_until(function_ref<bool(char)> F) const {
672 return substr(find_if(F));
675 /// Returns true if this StringRef has the given prefix and removes that
677 LLVM_ATTRIBUTE_ALWAYS_INLINE
678 bool consume_front(StringRef Prefix) {
679 if (!startswith(Prefix))
682 *this = drop_front(Prefix.size());
686 /// Returns true if this StringRef has the given suffix and removes that
688 LLVM_ATTRIBUTE_ALWAYS_INLINE
689 bool consume_back(StringRef Suffix) {
690 if (!endswith(Suffix))
693 *this = drop_back(Suffix.size());
697 /// Return a reference to the substring from [Start, End).
699 /// \param Start The index of the starting character in the substring; if
700 /// the index is npos or greater than the length of the string then the
701 /// empty substring will be returned.
703 /// \param End The index following the last character to include in the
704 /// substring. If this is npos or exceeds the number of characters
705 /// remaining in the string, the string suffix (starting with \p Start)
706 /// will be returned. If this is less than \p Start, an empty string will
709 LLVM_ATTRIBUTE_ALWAYS_INLINE
710 StringRef slice(size_t Start, size_t End) const {
711 Start = std::min(Start, Length);
712 End = std::min(std::max(Start, End), Length);
713 return StringRef(Data + Start, End - Start);
716 /// Split into two substrings around the first occurrence of a separator
719 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
720 /// such that (*this == LHS + Separator + RHS) is true and RHS is
721 /// maximal. If \p Separator is not in the string, then the result is a
722 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
724 /// \param Separator The character to split on.
725 /// \returns The split substrings.
727 std::pair<StringRef, StringRef> split(char Separator) const {
728 return split(StringRef(&Separator, 1));
731 /// Split into two substrings around the first occurrence of a separator
734 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
735 /// such that (*this == LHS + Separator + RHS) is true and RHS is
736 /// maximal. If \p Separator is not in the string, then the result is a
737 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
739 /// \param Separator - The string to split on.
740 /// \return - The split substrings.
742 std::pair<StringRef, StringRef> split(StringRef Separator) const {
743 size_t Idx = find(Separator);
745 return std::make_pair(*this, StringRef());
746 return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
749 /// Split into two substrings around the last occurrence of a separator
752 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
753 /// such that (*this == LHS + Separator + RHS) is true and RHS is
754 /// minimal. If \p Separator is not in the string, then the result is a
755 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
757 /// \param Separator - The string to split on.
758 /// \return - The split substrings.
760 std::pair<StringRef, StringRef> rsplit(StringRef Separator) const {
761 size_t Idx = rfind(Separator);
763 return std::make_pair(*this, StringRef());
764 return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
767 /// Split into substrings around the occurrences of a separator string.
769 /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
770 /// \p MaxSplit splits are done and consequently <= \p MaxSplit + 1
771 /// elements are added to A.
772 /// If \p KeepEmpty is false, empty strings are not added to \p A. They
773 /// still count when considering \p MaxSplit
774 /// An useful invariant is that
775 /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
777 /// \param A - Where to put the substrings.
778 /// \param Separator - The string to split on.
779 /// \param MaxSplit - The maximum number of times the string is split.
780 /// \param KeepEmpty - True if empty substring should be added.
781 void split(SmallVectorImpl<StringRef> &A,
782 StringRef Separator, int MaxSplit = -1,
783 bool KeepEmpty = true) const;
785 /// Split into substrings around the occurrences of a separator character.
787 /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
788 /// \p MaxSplit splits are done and consequently <= \p MaxSplit + 1
789 /// elements are added to A.
790 /// If \p KeepEmpty is false, empty strings are not added to \p A. They
791 /// still count when considering \p MaxSplit
792 /// An useful invariant is that
793 /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
795 /// \param A - Where to put the substrings.
796 /// \param Separator - The string to split on.
797 /// \param MaxSplit - The maximum number of times the string is split.
798 /// \param KeepEmpty - True if empty substring should be added.
799 void split(SmallVectorImpl<StringRef> &A, char Separator, int MaxSplit = -1,
800 bool KeepEmpty = true) const;
802 /// Split into two substrings around the last occurrence of a separator
805 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
806 /// such that (*this == LHS + Separator + RHS) is true and RHS is
807 /// minimal. If \p Separator is not in the string, then the result is a
808 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
810 /// \param Separator - The character to split on.
811 /// \return - The split substrings.
813 std::pair<StringRef, StringRef> rsplit(char Separator) const {
814 return rsplit(StringRef(&Separator, 1));
817 /// Return string with consecutive \p Char characters starting from the
818 /// the left removed.
820 StringRef ltrim(char Char) const {
821 return drop_front(std::min(Length, find_first_not_of(Char)));
824 /// Return string with consecutive characters in \p Chars starting from
825 /// the left removed.
827 StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
828 return drop_front(std::min(Length, find_first_not_of(Chars)));
831 /// Return string with consecutive \p Char characters starting from the
834 StringRef rtrim(char Char) const {
835 return drop_back(Length - std::min(Length, find_last_not_of(Char) + 1));
838 /// Return string with consecutive characters in \p Chars starting from
839 /// the right removed.
841 StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
842 return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
845 /// Return string with consecutive \p Char characters starting from the
846 /// left and right removed.
848 StringRef trim(char Char) const {
849 return ltrim(Char).rtrim(Char);
852 /// Return string with consecutive characters in \p Chars starting from
853 /// the left and right removed.
855 StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
856 return ltrim(Chars).rtrim(Chars);
862 /// A wrapper around a string literal that serves as a proxy for constructing
863 /// global tables of StringRefs with the length computed at compile time.
864 /// In order to avoid the invocation of a global constructor, StringLiteral
865 /// should *only* be used in a constexpr context, as such:
867 /// constexpr StringLiteral S("test");
869 class StringLiteral : public StringRef {
871 constexpr StringLiteral(const char *Str, size_t N) : StringRef(Str, N) {
876 constexpr StringLiteral(const char (&Str)[N])
877 #if defined(__clang__) && __has_attribute(enable_if)
878 #pragma clang diagnostic push
879 #pragma clang diagnostic ignored "-Wgcc-compat"
880 __attribute((enable_if(__builtin_strlen(Str) == N - 1,
881 "invalid string literal")))
882 #pragma clang diagnostic pop
884 : StringRef(Str, N - 1) {
887 // Explicit construction for strings like "foo\0bar".
889 static constexpr StringLiteral withInnerNUL(const char (&Str)[N]) {
890 return StringLiteral(Str, N - 1);
894 /// @name StringRef Comparison Operators
897 LLVM_ATTRIBUTE_ALWAYS_INLINE
898 inline bool operator==(StringRef LHS, StringRef RHS) {
899 return LHS.equals(RHS);
902 LLVM_ATTRIBUTE_ALWAYS_INLINE
903 inline bool operator!=(StringRef LHS, StringRef RHS) { return !(LHS == RHS); }
905 inline bool operator<(StringRef LHS, StringRef RHS) {
906 return LHS.compare(RHS) == -1;
909 inline bool operator<=(StringRef LHS, StringRef RHS) {
910 return LHS.compare(RHS) != 1;
913 inline bool operator>(StringRef LHS, StringRef RHS) {
914 return LHS.compare(RHS) == 1;
917 inline bool operator>=(StringRef LHS, StringRef RHS) {
918 return LHS.compare(RHS) != -1;
921 inline std::string &operator+=(std::string &buffer, StringRef string) {
922 return buffer.append(string.data(), string.size());
927 /// Compute a hash_code for a StringRef.
929 hash_code hash_value(StringRef S);
931 // StringRefs can be treated like a POD type.
932 template <typename T> struct isPodLike;
933 template <> struct isPodLike<StringRef> { static const bool value = true; };
935 } // end namespace llvm
937 #endif // LLVM_ADT_STRINGREF_H