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 LLVM_ATTRIBUTE_ALWAYS_INLINE
69 /*implicit*/ StringRef() : Data(nullptr), Length(0) {}
71 /// Construct a string ref from a cstring.
72 LLVM_ATTRIBUTE_ALWAYS_INLINE
73 /*implicit*/ StringRef(const char *Str)
75 assert(Str && "StringRef cannot be built from a NULL argument");
76 Length = ::strlen(Str); // invoking strlen(NULL) is undefined behavior
79 /// Construct a string ref from a pointer and length.
80 LLVM_ATTRIBUTE_ALWAYS_INLINE
81 /*implicit*/ StringRef(const char *data, size_t length)
82 : Data(data), Length(length) {
83 assert((data || length == 0) &&
84 "StringRef cannot be built from a NULL argument with non-null length");
87 /// Construct a string ref from an std::string.
88 LLVM_ATTRIBUTE_ALWAYS_INLINE
89 /*implicit*/ StringRef(const std::string &Str)
90 : Data(Str.data()), Length(Str.length()) {}
96 iterator begin() const { return Data; }
98 iterator end() const { return Data + Length; }
100 const unsigned char *bytes_begin() const {
101 return reinterpret_cast<const unsigned char *>(begin());
103 const unsigned char *bytes_end() const {
104 return reinterpret_cast<const unsigned char *>(end());
108 /// @name String Operations
111 /// data - Get a pointer to the start of the string (which may not be null
113 LLVM_ATTRIBUTE_ALWAYS_INLINE
114 const char *data() const { return Data; }
116 /// empty - Check if the string is empty.
117 LLVM_ATTRIBUTE_ALWAYS_INLINE
118 bool empty() const { return Length == 0; }
120 /// size - Get the string size.
121 LLVM_ATTRIBUTE_ALWAYS_INLINE
122 size_t size() const { return Length; }
124 /// front - Get the first character in the string.
130 /// back - Get the last character in the string.
133 return Data[Length-1];
136 // copy - Allocate copy in Allocator and return StringRef to it.
137 template <typename Allocator> StringRef copy(Allocator &A) const {
138 char *S = A.template Allocate<char>(Length);
139 std::copy(begin(), end(), S);
140 return StringRef(S, Length);
143 /// equals - Check for string equality, this is more efficient than
144 /// compare() when the relative ordering of inequal strings isn't needed.
145 LLVM_ATTRIBUTE_ALWAYS_INLINE
146 bool equals(StringRef RHS) const {
147 return (Length == RHS.Length &&
148 compareMemory(Data, RHS.Data, RHS.Length) == 0);
151 /// equals_lower - Check for string equality, ignoring case.
152 bool equals_lower(StringRef RHS) const {
153 return Length == RHS.Length && compare_lower(RHS) == 0;
156 /// compare - Compare two strings; the result is -1, 0, or 1 if this string
157 /// is lexicographically less than, equal to, or greater than the \p RHS.
158 LLVM_ATTRIBUTE_ALWAYS_INLINE
159 int compare(StringRef RHS) const {
160 // Check the prefix for a mismatch.
161 if (int Res = compareMemory(Data, RHS.Data, std::min(Length, RHS.Length)))
162 return Res < 0 ? -1 : 1;
164 // Otherwise the prefixes match, so we only need to check the lengths.
165 if (Length == RHS.Length)
167 return Length < RHS.Length ? -1 : 1;
170 /// compare_lower - Compare two strings, ignoring case.
171 int compare_lower(StringRef RHS) const;
173 /// compare_numeric - Compare two strings, treating sequences of digits as
175 int compare_numeric(StringRef RHS) const;
177 /// \brief Determine the edit distance between this string and another
180 /// \param Other the string to compare this string against.
182 /// \param AllowReplacements whether to allow character
183 /// replacements (change one character into another) as a single
184 /// operation, rather than as two operations (an insertion and a
187 /// \param MaxEditDistance If non-zero, the maximum edit distance that
188 /// this routine is allowed to compute. If the edit distance will exceed
189 /// that maximum, returns \c MaxEditDistance+1.
191 /// \returns the minimum number of character insertions, removals,
192 /// or (if \p AllowReplacements is \c true) replacements needed to
193 /// transform one of the given strings into the other. If zero,
194 /// the strings are identical.
195 unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
196 unsigned MaxEditDistance = 0) const;
198 /// str - Get the contents as an std::string.
199 std::string str() const {
200 if (!Data) return std::string();
201 return std::string(Data, Length);
205 /// @name Operator Overloads
208 char operator[](size_t Index) const {
209 assert(Index < Length && "Invalid index!");
214 /// @name Type Conversions
217 operator std::string() const {
222 /// @name String Predicates
225 /// Check if this string starts with the given \p Prefix.
226 LLVM_ATTRIBUTE_ALWAYS_INLINE
227 bool startswith(StringRef Prefix) const {
228 return Length >= Prefix.Length &&
229 compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
232 /// Check if this string starts with the given \p Prefix, ignoring case.
233 bool startswith_lower(StringRef Prefix) const;
235 /// Check if this string ends with the given \p Suffix.
236 LLVM_ATTRIBUTE_ALWAYS_INLINE
237 bool endswith(StringRef Suffix) const {
238 return Length >= Suffix.Length &&
239 compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
242 /// Check if this string ends with the given \p Suffix, ignoring case.
243 bool endswith_lower(StringRef Suffix) const;
246 /// @name String Searching
249 /// Search for the first character \p C in the string.
251 /// \returns The index of the first occurrence of \p C, or npos if not
253 LLVM_ATTRIBUTE_ALWAYS_INLINE
254 size_t find(char C, size_t From = 0) const {
255 size_t FindBegin = std::min(From, Length);
256 if (FindBegin < Length) { // Avoid calling memchr with nullptr.
257 // Just forward to memchr, which is faster than a hand-rolled loop.
258 if (const void *P = ::memchr(Data + FindBegin, C, Length - FindBegin))
259 return static_cast<const char *>(P) - Data;
264 /// Search for the first string \p Str in the string.
266 /// \returns The index of the first occurrence of \p Str, or npos if not
268 size_t find(StringRef Str, size_t From = 0) const;
270 /// Search for the last character \p C in the string.
272 /// \returns The index of the last occurrence of \p C, or npos if not
274 size_t rfind(char C, size_t From = npos) const {
275 From = std::min(From, Length);
285 /// Search for the last string \p Str in the string.
287 /// \returns The index of the last occurrence of \p Str, or npos if not
289 size_t rfind(StringRef Str) const;
291 /// Find the first character in the string that is \p C, or npos if not
292 /// found. Same as find.
293 size_t find_first_of(char C, size_t From = 0) const {
294 return find(C, From);
297 /// Find the first character in the string that is in \p Chars, or npos if
300 /// Complexity: O(size() + Chars.size())
301 size_t find_first_of(StringRef Chars, size_t From = 0) const;
303 /// Find the first character in the string that is not \p C or npos if not
305 size_t find_first_not_of(char C, size_t From = 0) const;
307 /// Find the first character in the string that is not in the string
308 /// \p Chars, or npos if not found.
310 /// Complexity: O(size() + Chars.size())
311 size_t find_first_not_of(StringRef Chars, size_t From = 0) const;
313 /// Find the last character in the string that is \p C, or npos if not
315 size_t find_last_of(char C, size_t From = npos) const {
316 return rfind(C, From);
319 /// Find the last character in the string that is in \p C, or npos if not
322 /// Complexity: O(size() + Chars.size())
323 size_t find_last_of(StringRef Chars, size_t From = npos) const;
325 /// Find the last character in the string that is not \p C, or npos if not
327 size_t find_last_not_of(char C, size_t From = npos) const;
329 /// Find the last character in the string that is not in \p Chars, or
330 /// npos if not found.
332 /// Complexity: O(size() + Chars.size())
333 size_t find_last_not_of(StringRef Chars, size_t From = npos) const;
336 /// @name Helpful Algorithms
339 /// Return the number of occurrences of \p C in the string.
340 size_t count(char C) const {
342 for (size_t i = 0, e = Length; i != e; ++i)
348 /// Return the number of non-overlapped occurrences of \p Str in
350 size_t count(StringRef Str) const;
352 /// Parse the current string as an integer of the specified radix. If
353 /// \p Radix is specified as zero, this does radix autosensing using
354 /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
356 /// If the string is invalid or if only a subset of the string is valid,
357 /// this returns true to signify the error. The string is considered
358 /// erroneous if empty or if it overflows T.
359 template <typename T>
360 typename std::enable_if<std::numeric_limits<T>::is_signed, bool>::type
361 getAsInteger(unsigned Radix, T &Result) const {
363 if (getAsSignedInteger(*this, Radix, LLVal) ||
364 static_cast<T>(LLVal) != LLVal)
370 template <typename T>
371 typename std::enable_if<!std::numeric_limits<T>::is_signed, bool>::type
372 getAsInteger(unsigned Radix, T &Result) const {
373 unsigned long long ULLVal;
374 // The additional cast to unsigned long long is required to avoid the
375 // Visual C++ warning C4805: '!=' : unsafe mix of type 'bool' and type
376 // 'unsigned __int64' when instantiating getAsInteger with T = bool.
377 if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
378 static_cast<unsigned long long>(static_cast<T>(ULLVal)) != ULLVal)
384 /// Parse the current string as an integer of the specified \p Radix, or of
385 /// an autosensed radix if the \p Radix given is 0. The current value in
386 /// \p Result is discarded, and the storage is changed to be wide enough to
387 /// store the parsed integer.
389 /// \returns true if the string does not solely consist of a valid
390 /// non-empty number in the appropriate base.
392 /// APInt::fromString is superficially similar but assumes the
393 /// string is well-formed in the given radix.
394 bool getAsInteger(unsigned Radix, APInt &Result) const;
397 /// @name String Operations
400 // Convert the given ASCII string to lowercase.
401 std::string lower() const;
403 /// Convert the given ASCII string to uppercase.
404 std::string upper() const;
407 /// @name Substring Operations
410 /// Return a reference to the substring from [Start, Start + N).
412 /// \param Start The index of the starting character in the substring; if
413 /// the index is npos or greater than the length of the string then the
414 /// empty substring will be returned.
416 /// \param N The number of characters to included in the substring. If N
417 /// exceeds the number of characters remaining in the string, the string
418 /// suffix (starting with \p Start) will be returned.
419 LLVM_ATTRIBUTE_ALWAYS_INLINE
420 StringRef substr(size_t Start, size_t N = npos) const {
421 Start = std::min(Start, Length);
422 return StringRef(Data + Start, std::min(N, Length - Start));
425 /// Return a StringRef equal to 'this' but with the first \p N elements
427 LLVM_ATTRIBUTE_ALWAYS_INLINE
428 StringRef drop_front(size_t N = 1) const {
429 assert(size() >= N && "Dropping more elements than exist");
433 /// Return a StringRef equal to 'this' but with the last \p N elements
435 LLVM_ATTRIBUTE_ALWAYS_INLINE
436 StringRef drop_back(size_t N = 1) const {
437 assert(size() >= N && "Dropping more elements than exist");
438 return substr(0, size()-N);
441 /// Return a reference to the substring from [Start, End).
443 /// \param Start The index of the starting character in the substring; if
444 /// the index is npos or greater than the length of the string then the
445 /// empty substring will be returned.
447 /// \param End The index following the last character to include in the
448 /// substring. If this is npos, or less than \p Start, or exceeds the
449 /// number of characters remaining in the string, the string suffix
450 /// (starting with \p Start) will be returned.
451 LLVM_ATTRIBUTE_ALWAYS_INLINE
452 StringRef slice(size_t Start, size_t End) const {
453 Start = std::min(Start, Length);
454 End = std::min(std::max(Start, End), Length);
455 return StringRef(Data + Start, End - Start);
458 /// Split into two substrings around the first occurrence of a separator
461 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
462 /// such that (*this == LHS + Separator + RHS) is true and RHS is
463 /// maximal. If \p Separator is not in the string, then the result is a
464 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
466 /// \param Separator The character to split on.
467 /// \returns The split substrings.
468 std::pair<StringRef, StringRef> split(char Separator) const {
469 size_t Idx = find(Separator);
471 return std::make_pair(*this, StringRef());
472 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
475 /// Split into two substrings around the first occurrence of a separator
478 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
479 /// such that (*this == LHS + Separator + RHS) is true and RHS is
480 /// maximal. If \p Separator is not in the string, then the result is a
481 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
483 /// \param Separator - The string to split on.
484 /// \return - The split substrings.
485 std::pair<StringRef, StringRef> split(StringRef Separator) const {
486 size_t Idx = find(Separator);
488 return std::make_pair(*this, StringRef());
489 return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
492 /// Split into substrings around the occurrences of a separator string.
494 /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
495 /// \p MaxSplit splits are done and consequently <= \p MaxSplit + 1
496 /// elements are added to A.
497 /// If \p KeepEmpty is false, empty strings are not added to \p A. They
498 /// still count when considering \p MaxSplit
499 /// An useful invariant is that
500 /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
502 /// \param A - Where to put the substrings.
503 /// \param Separator - The string to split on.
504 /// \param MaxSplit - The maximum number of times the string is split.
505 /// \param KeepEmpty - True if empty substring should be added.
506 void split(SmallVectorImpl<StringRef> &A,
507 StringRef Separator, int MaxSplit = -1,
508 bool KeepEmpty = true) const;
510 /// Split into substrings around the occurrences of a separator character.
512 /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
513 /// \p MaxSplit splits are done and consequently <= \p MaxSplit + 1
514 /// elements are added to A.
515 /// If \p KeepEmpty is false, empty strings are not added to \p A. They
516 /// still count when considering \p MaxSplit
517 /// An useful invariant is that
518 /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
520 /// \param A - Where to put the substrings.
521 /// \param Separator - The string to split on.
522 /// \param MaxSplit - The maximum number of times the string is split.
523 /// \param KeepEmpty - True if empty substring should be added.
524 void split(SmallVectorImpl<StringRef> &A, char Separator, int MaxSplit = -1,
525 bool KeepEmpty = true) const;
527 /// Split into two substrings around the last occurrence of a separator
530 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
531 /// such that (*this == LHS + Separator + RHS) is true and RHS is
532 /// minimal. If \p Separator is not in the string, then the result is a
533 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
535 /// \param Separator - The character to split on.
536 /// \return - The split substrings.
537 std::pair<StringRef, StringRef> rsplit(char Separator) const {
538 size_t Idx = rfind(Separator);
540 return std::make_pair(*this, StringRef());
541 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
544 /// Return string with consecutive characters in \p Chars starting from
545 /// the left removed.
546 StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
547 return drop_front(std::min(Length, find_first_not_of(Chars)));
550 /// Return string with consecutive characters in \p Chars starting from
551 /// the right removed.
552 StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
553 return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
556 /// Return string with consecutive characters in \p Chars starting from
557 /// the left and right removed.
558 StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
559 return ltrim(Chars).rtrim(Chars);
565 /// @name StringRef Comparison Operators
568 LLVM_ATTRIBUTE_ALWAYS_INLINE
569 inline bool operator==(StringRef LHS, StringRef RHS) {
570 return LHS.equals(RHS);
573 LLVM_ATTRIBUTE_ALWAYS_INLINE
574 inline bool operator!=(StringRef LHS, StringRef RHS) {
575 return !(LHS == RHS);
578 inline bool operator<(StringRef LHS, StringRef RHS) {
579 return LHS.compare(RHS) == -1;
582 inline bool operator<=(StringRef LHS, StringRef RHS) {
583 return LHS.compare(RHS) != 1;
586 inline bool operator>(StringRef LHS, StringRef RHS) {
587 return LHS.compare(RHS) == 1;
590 inline bool operator>=(StringRef LHS, StringRef RHS) {
591 return LHS.compare(RHS) != -1;
594 inline std::string &operator+=(std::string &buffer, StringRef string) {
595 return buffer.append(string.data(), string.size());
600 /// \brief Compute a hash_code for a StringRef.
601 hash_code hash_value(StringRef S);
603 // StringRefs can be treated like a POD type.
604 template <typename T> struct isPodLike;
605 template <> struct isPodLike<StringRef> { static const bool value = true; };