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/Support/Compiler.h"
23 class SmallVectorImpl;
28 /// Helper functions for StringRef::getAsInteger.
29 bool getAsUnsignedInteger(StringRef Str, unsigned Radix,
30 unsigned long long &Result);
32 bool getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result);
34 /// StringRef - Represent a constant reference to a string, i.e. a character
35 /// array and a length, which need not be null terminated.
37 /// This class does not own the string data, it is expected to be used in
38 /// situations where the character data resides in some other buffer, whose
39 /// lifetime extends past that of the StringRef. For this reason, it is not in
40 /// general safe to store a StringRef.
43 typedef const char *iterator;
44 typedef const char *const_iterator;
45 static const size_t npos = ~size_t(0);
46 typedef size_t size_type;
49 /// The start of the string, in an external buffer.
52 /// The length of the string.
55 // Workaround memcmp issue with null pointers (undefined behavior)
56 // by providing a specialized version
57 LLVM_ATTRIBUTE_ALWAYS_INLINE
58 static int compareMemory(const char *Lhs, const char *Rhs, size_t Length) {
59 if (Length == 0) { return 0; }
60 return ::memcmp(Lhs,Rhs,Length);
64 /// @name Constructors
67 /// Construct an empty string ref.
68 /*implicit*/ StringRef() : Data(nullptr), Length(0) {}
70 /// Construct a string ref from a cstring.
71 /*implicit*/ StringRef(const char *Str)
73 assert(Str && "StringRef cannot be built from a NULL argument");
74 Length = ::strlen(Str); // invoking strlen(NULL) is undefined behavior
77 /// Construct a string ref from a pointer and length.
78 LLVM_ATTRIBUTE_ALWAYS_INLINE
79 /*implicit*/ StringRef(const char *data, size_t length)
80 : Data(data), Length(length) {
81 assert((data || length == 0) &&
82 "StringRef cannot be built from a NULL argument with non-null length");
85 /// Construct a string ref from an std::string.
86 LLVM_ATTRIBUTE_ALWAYS_INLINE
87 /*implicit*/ StringRef(const std::string &Str)
88 : Data(Str.data()), Length(Str.length()) {}
94 iterator begin() const { return Data; }
96 iterator end() const { return Data + Length; }
98 const unsigned char *bytes_begin() const {
99 return reinterpret_cast<const unsigned char *>(begin());
101 const unsigned char *bytes_end() const {
102 return reinterpret_cast<const unsigned char *>(end());
106 /// @name String Operations
109 /// data - Get a pointer to the start of the string (which may not be null
111 LLVM_ATTRIBUTE_ALWAYS_INLINE
112 const char *data() const { return Data; }
114 /// empty - Check if the string is empty.
115 LLVM_ATTRIBUTE_ALWAYS_INLINE
116 bool empty() const { return Length == 0; }
118 /// size - Get the string size.
119 LLVM_ATTRIBUTE_ALWAYS_INLINE
120 size_t size() const { return Length; }
122 /// front - Get the first character in the string.
128 /// back - Get the last character in the string.
131 return Data[Length-1];
134 // copy - Allocate copy in Allocator and return StringRef to it.
135 template <typename Allocator> StringRef copy(Allocator &A) const {
136 char *S = A.template Allocate<char>(Length);
137 std::copy(begin(), end(), S);
138 return StringRef(S, Length);
141 /// equals - Check for string equality, this is more efficient than
142 /// compare() when the relative ordering of inequal strings isn't needed.
143 LLVM_ATTRIBUTE_ALWAYS_INLINE
144 bool equals(StringRef RHS) const {
145 return (Length == RHS.Length &&
146 compareMemory(Data, RHS.Data, RHS.Length) == 0);
149 /// equals_lower - Check for string equality, ignoring case.
150 bool equals_lower(StringRef RHS) const {
151 return Length == RHS.Length && compare_lower(RHS) == 0;
154 /// compare - Compare two strings; the result is -1, 0, or 1 if this string
155 /// is lexicographically less than, equal to, or greater than the \p RHS.
156 LLVM_ATTRIBUTE_ALWAYS_INLINE
157 int compare(StringRef RHS) const {
158 // Check the prefix for a mismatch.
159 if (int Res = compareMemory(Data, RHS.Data, std::min(Length, RHS.Length)))
160 return Res < 0 ? -1 : 1;
162 // Otherwise the prefixes match, so we only need to check the lengths.
163 if (Length == RHS.Length)
165 return Length < RHS.Length ? -1 : 1;
168 /// compare_lower - Compare two strings, ignoring case.
169 int compare_lower(StringRef RHS) const;
171 /// compare_numeric - Compare two strings, treating sequences of digits as
173 int compare_numeric(StringRef RHS) const;
175 /// \brief Determine the edit distance between this string and another
178 /// \param Other the string to compare this string against.
180 /// \param AllowReplacements whether to allow character
181 /// replacements (change one character into another) as a single
182 /// operation, rather than as two operations (an insertion and a
185 /// \param MaxEditDistance If non-zero, the maximum edit distance that
186 /// this routine is allowed to compute. If the edit distance will exceed
187 /// that maximum, returns \c MaxEditDistance+1.
189 /// \returns the minimum number of character insertions, removals,
190 /// or (if \p AllowReplacements is \c true) replacements needed to
191 /// transform one of the given strings into the other. If zero,
192 /// the strings are identical.
193 unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
194 unsigned MaxEditDistance = 0) const;
196 /// str - Get the contents as an std::string.
197 std::string str() const {
198 if (!Data) return std::string();
199 return std::string(Data, Length);
203 /// @name Operator Overloads
206 char operator[](size_t Index) const {
207 assert(Index < Length && "Invalid index!");
212 /// @name Type Conversions
215 operator std::string() const {
220 /// @name String Predicates
223 /// Check if this string starts with the given \p Prefix.
224 LLVM_ATTRIBUTE_ALWAYS_INLINE
225 bool startswith(StringRef Prefix) const {
226 return Length >= Prefix.Length &&
227 compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
230 /// Check if this string starts with the given \p Prefix, ignoring case.
231 bool startswith_lower(StringRef Prefix) const;
233 /// Check if this string ends with the given \p Suffix.
234 LLVM_ATTRIBUTE_ALWAYS_INLINE
235 bool endswith(StringRef Suffix) const {
236 return Length >= Suffix.Length &&
237 compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
240 /// Check if this string ends with the given \p Suffix, ignoring case.
241 bool endswith_lower(StringRef Suffix) const;
244 /// @name String Searching
247 /// Search for the first character \p C in the string.
249 /// \returns The index of the first occurrence of \p C, or npos if not
251 LLVM_ATTRIBUTE_ALWAYS_INLINE
252 size_t find(char C, size_t From = 0) const {
253 size_t FindBegin = std::min(From, Length);
254 if (FindBegin < Length) { // Avoid calling memchr with nullptr.
255 // Just forward to memchr, which is faster than a hand-rolled loop.
256 if (const void *P = ::memchr(Data + FindBegin, C, Length - FindBegin))
257 return static_cast<const char *>(P) - Data;
262 /// Search for the first string \p Str in the string.
264 /// \returns The index of the first occurrence of \p Str, or npos if not
266 size_t find(StringRef Str, size_t From = 0) const;
268 /// Search for the last character \p C in the string.
270 /// \returns The index of the last occurrence of \p C, or npos if not
272 size_t rfind(char C, size_t From = npos) const {
273 From = std::min(From, Length);
283 /// Search for the last string \p Str in the string.
285 /// \returns The index of the last occurrence of \p Str, or npos if not
287 size_t rfind(StringRef Str) const;
289 /// Find the first character in the string that is \p C, or npos if not
290 /// found. Same as find.
291 size_t find_first_of(char C, size_t From = 0) const {
292 return find(C, From);
295 /// Find the first character in the string that is in \p Chars, or npos if
298 /// Complexity: O(size() + Chars.size())
299 size_t find_first_of(StringRef Chars, size_t From = 0) const;
301 /// Find the first character in the string that is not \p C or npos if not
303 size_t find_first_not_of(char C, size_t From = 0) const;
305 /// Find the first character in the string that is not in the string
306 /// \p Chars, or npos if not found.
308 /// Complexity: O(size() + Chars.size())
309 size_t find_first_not_of(StringRef Chars, size_t From = 0) const;
311 /// Find the last character in the string that is \p C, or npos if not
313 size_t find_last_of(char C, size_t From = npos) const {
314 return rfind(C, From);
317 /// Find the last character in the string that is in \p C, or npos if not
320 /// Complexity: O(size() + Chars.size())
321 size_t find_last_of(StringRef Chars, size_t From = npos) const;
323 /// Find the last character in the string that is not \p C, or npos if not
325 size_t find_last_not_of(char C, size_t From = npos) const;
327 /// Find the last character in the string that is not in \p Chars, or
328 /// npos if not found.
330 /// Complexity: O(size() + Chars.size())
331 size_t find_last_not_of(StringRef Chars, size_t From = npos) const;
334 /// @name Helpful Algorithms
337 /// Return the number of occurrences of \p C in the string.
338 size_t count(char C) const {
340 for (size_t i = 0, e = Length; i != e; ++i)
346 /// Return the number of non-overlapped occurrences of \p Str in
348 size_t count(StringRef Str) const;
350 /// Parse the current string as an integer of the specified radix. If
351 /// \p Radix is specified as zero, this does radix autosensing using
352 /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
354 /// If the string is invalid or if only a subset of the string is valid,
355 /// this returns true to signify the error. The string is considered
356 /// erroneous if empty or if it overflows T.
357 template <typename T>
358 typename std::enable_if<std::numeric_limits<T>::is_signed, bool>::type
359 getAsInteger(unsigned Radix, T &Result) const {
361 if (getAsSignedInteger(*this, Radix, LLVal) ||
362 static_cast<T>(LLVal) != LLVal)
368 template <typename T>
369 typename std::enable_if<!std::numeric_limits<T>::is_signed, bool>::type
370 getAsInteger(unsigned Radix, T &Result) const {
371 unsigned long long ULLVal;
372 // The additional cast to unsigned long long is required to avoid the
373 // Visual C++ warning C4805: '!=' : unsafe mix of type 'bool' and type
374 // 'unsigned __int64' when instantiating getAsInteger with T = bool.
375 if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
376 static_cast<unsigned long long>(static_cast<T>(ULLVal)) != ULLVal)
382 /// Parse the current string as an integer of the specified \p Radix, or of
383 /// an autosensed radix if the \p Radix given is 0. The current value in
384 /// \p Result is discarded, and the storage is changed to be wide enough to
385 /// store the parsed integer.
387 /// \returns true if the string does not solely consist of a valid
388 /// non-empty number in the appropriate base.
390 /// APInt::fromString is superficially similar but assumes the
391 /// string is well-formed in the given radix.
392 bool getAsInteger(unsigned Radix, APInt &Result) const;
395 /// @name String Operations
398 // Convert the given ASCII string to lowercase.
399 std::string lower() const;
401 /// Convert the given ASCII string to uppercase.
402 std::string upper() const;
405 /// @name Substring Operations
408 /// Return a reference to the substring from [Start, Start + N).
410 /// \param Start The index of the starting character in the substring; if
411 /// the index is npos or greater than the length of the string then the
412 /// empty substring will be returned.
414 /// \param N The number of characters to included in the substring. If N
415 /// exceeds the number of characters remaining in the string, the string
416 /// suffix (starting with \p Start) will be returned.
417 LLVM_ATTRIBUTE_ALWAYS_INLINE
418 StringRef substr(size_t Start, size_t N = npos) const {
419 Start = std::min(Start, Length);
420 return StringRef(Data + Start, std::min(N, Length - Start));
423 /// Return a StringRef equal to 'this' but with the first \p N elements
425 LLVM_ATTRIBUTE_ALWAYS_INLINE
426 StringRef drop_front(size_t N = 1) const {
427 assert(size() >= N && "Dropping more elements than exist");
431 /// Return a StringRef equal to 'this' but with the last \p N elements
433 LLVM_ATTRIBUTE_ALWAYS_INLINE
434 StringRef drop_back(size_t N = 1) const {
435 assert(size() >= N && "Dropping more elements than exist");
436 return substr(0, size()-N);
439 /// Return a reference to the substring from [Start, End).
441 /// \param Start The index of the starting character in the substring; if
442 /// the index is npos or greater than the length of the string then the
443 /// empty substring will be returned.
445 /// \param End The index following the last character to include in the
446 /// substring. If this is npos, or less than \p Start, or exceeds the
447 /// number of characters remaining in the string, the string suffix
448 /// (starting with \p Start) will be returned.
449 LLVM_ATTRIBUTE_ALWAYS_INLINE
450 StringRef slice(size_t Start, size_t End) const {
451 Start = std::min(Start, Length);
452 End = std::min(std::max(Start, End), Length);
453 return StringRef(Data + Start, End - Start);
456 /// Split into two substrings around the first occurrence of a separator
459 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
460 /// such that (*this == LHS + Separator + RHS) is true and RHS is
461 /// maximal. If \p Separator is not in the string, then the result is a
462 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
464 /// \param Separator The character to split on.
465 /// \returns The split substrings.
466 std::pair<StringRef, StringRef> split(char Separator) const {
467 size_t Idx = find(Separator);
469 return std::make_pair(*this, StringRef());
470 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
473 /// Split into two substrings around the first occurrence of a separator
476 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
477 /// such that (*this == LHS + Separator + RHS) is true and RHS is
478 /// maximal. If \p Separator is not in the string, then the result is a
479 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
481 /// \param Separator - The string to split on.
482 /// \return - The split substrings.
483 std::pair<StringRef, StringRef> split(StringRef Separator) const {
484 size_t Idx = find(Separator);
486 return std::make_pair(*this, StringRef());
487 return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
490 /// Split into substrings around the occurrences of a separator string.
492 /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
493 /// \p MaxSplit splits are done and consequently <= \p MaxSplit + 1
494 /// elements are added to A.
495 /// If \p KeepEmpty is false, empty strings are not added to \p A. They
496 /// still count when considering \p MaxSplit
497 /// An useful invariant is that
498 /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
500 /// \param A - Where to put the substrings.
501 /// \param Separator - The string to split on.
502 /// \param MaxSplit - The maximum number of times the string is split.
503 /// \param KeepEmpty - True if empty substring should be added.
504 void split(SmallVectorImpl<StringRef> &A,
505 StringRef Separator, int MaxSplit = -1,
506 bool KeepEmpty = true) const;
508 /// Split into substrings around the occurrences of a separator character.
510 /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
511 /// \p MaxSplit splits are done and consequently <= \p MaxSplit + 1
512 /// elements are added to A.
513 /// If \p KeepEmpty is false, empty strings are not added to \p A. They
514 /// still count when considering \p MaxSplit
515 /// An useful invariant is that
516 /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
518 /// \param A - Where to put the substrings.
519 /// \param Separator - The string to split on.
520 /// \param MaxSplit - The maximum number of times the string is split.
521 /// \param KeepEmpty - True if empty substring should be added.
522 void split(SmallVectorImpl<StringRef> &A, char Separator, int MaxSplit = -1,
523 bool KeepEmpty = true) const;
525 /// Split into two substrings around the last occurrence of a separator
528 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
529 /// such that (*this == LHS + Separator + RHS) is true and RHS is
530 /// minimal. If \p Separator is not in the string, then the result is a
531 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
533 /// \param Separator - The character to split on.
534 /// \return - The split substrings.
535 std::pair<StringRef, StringRef> rsplit(char Separator) const {
536 size_t Idx = rfind(Separator);
538 return std::make_pair(*this, StringRef());
539 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
542 /// Return string with consecutive characters in \p Chars starting from
543 /// the left removed.
544 StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
545 return drop_front(std::min(Length, find_first_not_of(Chars)));
548 /// Return string with consecutive characters in \p Chars starting from
549 /// the right removed.
550 StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
551 return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
554 /// Return string with consecutive characters in \p Chars starting from
555 /// the left and right removed.
556 StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
557 return ltrim(Chars).rtrim(Chars);
563 /// @name StringRef Comparison Operators
566 LLVM_ATTRIBUTE_ALWAYS_INLINE
567 inline bool operator==(StringRef LHS, StringRef RHS) {
568 return LHS.equals(RHS);
571 LLVM_ATTRIBUTE_ALWAYS_INLINE
572 inline bool operator!=(StringRef LHS, StringRef RHS) {
573 return !(LHS == RHS);
576 inline bool operator<(StringRef LHS, StringRef RHS) {
577 return LHS.compare(RHS) == -1;
580 inline bool operator<=(StringRef LHS, StringRef RHS) {
581 return LHS.compare(RHS) != 1;
584 inline bool operator>(StringRef LHS, StringRef RHS) {
585 return LHS.compare(RHS) == 1;
588 inline bool operator>=(StringRef LHS, StringRef RHS) {
589 return LHS.compare(RHS) != -1;
592 inline std::string &operator+=(std::string &buffer, StringRef string) {
593 return buffer.append(string.data(), string.size());
598 /// \brief Compute a hash_code for a StringRef.
599 hash_code hash_value(StringRef S);
601 // StringRefs can be treated like a POD type.
602 template <typename T> struct isPodLike;
603 template <> struct isPodLike<StringRef> { static const bool value = true; };