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
22 class SmallVectorImpl;
27 /// Helper functions for StringRef::getAsInteger.
28 bool getAsUnsignedInteger(StringRef Str, unsigned Radix,
29 unsigned long long &Result);
31 bool getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result);
33 /// StringRef - Represent a constant reference to a string, i.e. a character
34 /// array and a length, which need not be null terminated.
36 /// This class does not own the string data, it is expected to be used in
37 /// situations where the character data resides in some other buffer, whose
38 /// lifetime extends past that of the StringRef. For this reason, it is not in
39 /// general safe to store a StringRef.
42 typedef const char *iterator;
43 typedef const char *const_iterator;
44 static const size_t npos = ~size_t(0);
45 typedef size_t size_type;
48 /// The start of the string, in an external buffer.
51 /// The length of the string.
54 // Workaround PR5482: nearly all gcc 4.x miscompile StringRef and std::min()
55 // Changing the arg of min to be an integer, instead of a reference to an
56 // integer works around this bug.
57 static size_t min(size_t a, size_t b) { return a < b ? a : b; }
58 static size_t max(size_t a, size_t b) { return a > b ? a : b; }
60 // Workaround memcmp issue with null pointers (undefined behavior)
61 // by providing a specialized version
62 static int compareMemory(const char *Lhs, const char *Rhs, size_t Length) {
63 if (Length == 0) { return 0; }
64 return ::memcmp(Lhs,Rhs,Length);
68 /// @name Constructors
71 /// Construct an empty string ref.
72 /*implicit*/ StringRef() : Data(nullptr), Length(0) {}
74 /// Construct a string ref from a cstring.
75 /*implicit*/ StringRef(const char *Str)
77 assert(Str && "StringRef cannot be built from a NULL argument");
78 Length = ::strlen(Str); // invoking strlen(NULL) is undefined behavior
81 /// Construct a string ref from a pointer and length.
82 /*implicit*/ StringRef(const char *data, size_t length)
83 : Data(data), Length(length) {
84 assert((data || length == 0) &&
85 "StringRef cannot be built from a NULL argument with non-null length");
88 /// Construct a string ref from an std::string.
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; }
101 /// @name String Operations
104 /// data - Get a pointer to the start of the string (which may not be null
106 const char *data() const { return Data; }
108 /// empty - Check if the string is empty.
109 bool empty() const { return Length == 0; }
111 /// size - Get the string size.
112 size_t size() const { return Length; }
114 /// front - Get the first character in the string.
120 /// back - Get the last character in the string.
123 return Data[Length-1];
126 // copy - Allocate copy in Allocator and return StringRef to it.
127 template <typename Allocator> StringRef copy(Allocator &A) {
128 char *S = A.template Allocate<char>(Length);
129 std::copy(begin(), end(), S);
130 return StringRef(S, Length);
133 /// equals - Check for string equality, this is more efficient than
134 /// compare() when the relative ordering of inequal strings isn't needed.
135 bool equals(StringRef RHS) const {
136 return (Length == RHS.Length &&
137 compareMemory(Data, RHS.Data, RHS.Length) == 0);
140 /// equals_lower - Check for string equality, ignoring case.
141 bool equals_lower(StringRef RHS) const {
142 return Length == RHS.Length && compare_lower(RHS) == 0;
145 /// compare - Compare two strings; the result is -1, 0, or 1 if this string
146 /// is lexicographically less than, equal to, or greater than the \p RHS.
147 int compare(StringRef RHS) const {
148 // Check the prefix for a mismatch.
149 if (int Res = compareMemory(Data, RHS.Data, min(Length, RHS.Length)))
150 return Res < 0 ? -1 : 1;
152 // Otherwise the prefixes match, so we only need to check the lengths.
153 if (Length == RHS.Length)
155 return Length < RHS.Length ? -1 : 1;
158 /// compare_lower - Compare two strings, ignoring case.
159 int compare_lower(StringRef RHS) const;
161 /// compare_numeric - Compare two strings, treating sequences of digits as
163 int compare_numeric(StringRef RHS) const;
165 /// \brief Determine the edit distance between this string and another
168 /// \param Other the string to compare this string against.
170 /// \param AllowReplacements whether to allow character
171 /// replacements (change one character into another) as a single
172 /// operation, rather than as two operations (an insertion and a
175 /// \param MaxEditDistance If non-zero, the maximum edit distance that
176 /// this routine is allowed to compute. If the edit distance will exceed
177 /// that maximum, returns \c MaxEditDistance+1.
179 /// \returns the minimum number of character insertions, removals,
180 /// or (if \p AllowReplacements is \c true) replacements needed to
181 /// transform one of the given strings into the other. If zero,
182 /// the strings are identical.
183 unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
184 unsigned MaxEditDistance = 0) const;
186 /// str - Get the contents as an std::string.
187 std::string str() const {
188 if (!Data) return std::string();
189 return std::string(Data, Length);
193 /// @name Operator Overloads
196 char operator[](size_t Index) const {
197 assert(Index < Length && "Invalid index!");
202 /// @name Type Conversions
205 operator std::string() const {
210 /// @name String Predicates
213 /// Check if this string starts with the given \p Prefix.
214 bool startswith(StringRef Prefix) const {
215 return Length >= Prefix.Length &&
216 compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
219 /// Check if this string starts with the given \p Prefix, ignoring case.
220 bool startswith_lower(StringRef Prefix) const;
222 /// Check if this string ends with the given \p Suffix.
223 bool endswith(StringRef Suffix) const {
224 return Length >= Suffix.Length &&
225 compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
228 /// Check if this string ends with the given \p Suffix, ignoring case.
229 bool endswith_lower(StringRef Suffix) const;
232 /// @name String Searching
235 /// Search for the first character \p C in the string.
237 /// \returns The index of the first occurrence of \p C, or npos if not
239 size_t find(char C, size_t From = 0) const {
240 for (size_t i = min(From, Length), e = Length; i != e; ++i)
246 /// Search for the first string \p Str in the string.
248 /// \returns The index of the first occurrence of \p Str, or npos if not
250 size_t find(StringRef Str, size_t From = 0) const;
252 /// Search for the last character \p C in the string.
254 /// \returns The index of the last occurrence of \p C, or npos if not
256 size_t rfind(char C, size_t From = npos) const {
257 From = min(From, Length);
267 /// Search for the last string \p Str in the string.
269 /// \returns The index of the last occurrence of \p Str, or npos if not
271 size_t rfind(StringRef Str) const;
273 /// Find the first character in the string that is \p C, or npos if not
274 /// found. Same as find.
275 size_t find_first_of(char C, size_t From = 0) const {
276 return find(C, From);
279 /// Find the first character in the string that is in \p Chars, or npos if
282 /// Complexity: O(size() + Chars.size())
283 size_t find_first_of(StringRef Chars, size_t From = 0) const;
285 /// Find the first character in the string that is not \p C or npos if not
287 size_t find_first_not_of(char C, size_t From = 0) const;
289 /// Find the first character in the string that is not in the string
290 /// \p Chars, or npos if not found.
292 /// Complexity: O(size() + Chars.size())
293 size_t find_first_not_of(StringRef Chars, size_t From = 0) const;
295 /// Find the last character in the string that is \p C, or npos if not
297 size_t find_last_of(char C, size_t From = npos) const {
298 return rfind(C, From);
301 /// Find the last character in the string that is in \p C, or npos if not
304 /// Complexity: O(size() + Chars.size())
305 size_t find_last_of(StringRef Chars, size_t From = npos) const;
307 /// Find the last character in the string that is not \p C, or npos if not
309 size_t find_last_not_of(char C, size_t From = npos) const;
311 /// Find the last character in the string that is not in \p Chars, or
312 /// npos if not found.
314 /// Complexity: O(size() + Chars.size())
315 size_t find_last_not_of(StringRef Chars, size_t From = npos) const;
318 /// @name Helpful Algorithms
321 /// Return the number of occurrences of \p C in the string.
322 size_t count(char C) const {
324 for (size_t i = 0, e = Length; i != e; ++i)
330 /// Return the number of non-overlapped occurrences of \p Str in
332 size_t count(StringRef Str) const;
334 /// Parse the current string as an integer of the specified radix. If
335 /// \p Radix is specified as zero, this does radix autosensing using
336 /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
338 /// If the string is invalid or if only a subset of the string is valid,
339 /// this returns true to signify the error. The string is considered
340 /// erroneous if empty or if it overflows T.
341 template <typename T>
342 typename std::enable_if<std::numeric_limits<T>::is_signed, bool>::type
343 getAsInteger(unsigned Radix, T &Result) const {
345 if (getAsSignedInteger(*this, Radix, LLVal) ||
346 static_cast<T>(LLVal) != LLVal)
352 template <typename T>
353 typename std::enable_if<!std::numeric_limits<T>::is_signed, bool>::type
354 getAsInteger(unsigned Radix, T &Result) const {
355 unsigned long long ULLVal;
356 if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
357 static_cast<T>(ULLVal) != ULLVal)
363 /// Parse the current string as an integer of the specified \p Radix, or of
364 /// an autosensed radix if the \p Radix given is 0. The current value in
365 /// \p Result is discarded, and the storage is changed to be wide enough to
366 /// store the parsed integer.
368 /// \returns true if the string does not solely consist of a valid
369 /// non-empty number in the appropriate base.
371 /// APInt::fromString is superficially similar but assumes the
372 /// string is well-formed in the given radix.
373 bool getAsInteger(unsigned Radix, APInt &Result) const;
376 /// @name String Operations
379 // Convert the given ASCII string to lowercase.
380 std::string lower() const;
382 /// Convert the given ASCII string to uppercase.
383 std::string upper() const;
386 /// @name Substring Operations
389 /// Return a reference to the substring from [Start, Start + N).
391 /// \param Start The index of the starting character in the substring; if
392 /// the index is npos or greater than the length of the string then the
393 /// empty substring will be returned.
395 /// \param N The number of characters to included in the substring. If N
396 /// exceeds the number of characters remaining in the string, the string
397 /// suffix (starting with \p Start) will be returned.
398 StringRef substr(size_t Start, size_t N = npos) const {
399 Start = min(Start, Length);
400 return StringRef(Data + Start, min(N, Length - Start));
403 /// Return a StringRef equal to 'this' but with the first \p N elements
405 StringRef drop_front(size_t N = 1) const {
406 assert(size() >= N && "Dropping more elements than exist");
410 /// Return a StringRef equal to 'this' but with the last \p N elements
412 StringRef drop_back(size_t N = 1) const {
413 assert(size() >= N && "Dropping more elements than exist");
414 return substr(0, size()-N);
417 /// Return a reference to the substring from [Start, End).
419 /// \param Start The index of the starting character in the substring; if
420 /// the index is npos or greater than the length of the string then the
421 /// empty substring will be returned.
423 /// \param End The index following the last character to include in the
424 /// substring. If this is npos, or less than \p Start, or exceeds the
425 /// number of characters remaining in the string, the string suffix
426 /// (starting with \p Start) will be returned.
427 StringRef slice(size_t Start, size_t End) const {
428 Start = min(Start, Length);
429 End = min(max(Start, End), Length);
430 return StringRef(Data + Start, End - Start);
433 /// Split into two substrings around the first occurrence of a separator
436 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
437 /// such that (*this == LHS + Separator + RHS) is true and RHS is
438 /// maximal. If \p Separator is not in the string, then the result is a
439 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
441 /// \param Separator The character to split on.
442 /// \returns The split substrings.
443 std::pair<StringRef, StringRef> split(char Separator) const {
444 size_t Idx = find(Separator);
446 return std::make_pair(*this, StringRef());
447 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
450 /// Split into two substrings around the first occurrence of a separator
453 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
454 /// such that (*this == LHS + Separator + RHS) is true and RHS is
455 /// maximal. If \p Separator is not in the string, then the result is a
456 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
458 /// \param Separator - The string to split on.
459 /// \return - The split substrings.
460 std::pair<StringRef, StringRef> split(StringRef Separator) const {
461 size_t Idx = find(Separator);
463 return std::make_pair(*this, StringRef());
464 return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
467 /// Split into substrings around the occurrences of a separator string.
469 /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
470 /// \p MaxSplit splits are done and consequently <= \p MaxSplit
471 /// elements are added to A.
472 /// If \p KeepEmpty is false, empty strings are not added to \p A. They
473 /// still count when considering \p MaxSplit
474 /// An useful invariant is that
475 /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
477 /// \param A - Where to put the substrings.
478 /// \param Separator - The string to split on.
479 /// \param MaxSplit - The maximum number of times the string is split.
480 /// \param KeepEmpty - True if empty substring should be added.
481 void split(SmallVectorImpl<StringRef> &A,
482 StringRef Separator, int MaxSplit = -1,
483 bool KeepEmpty = true) const;
485 /// Split into two substrings around the last occurrence of a separator
488 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
489 /// such that (*this == LHS + Separator + RHS) is true and RHS is
490 /// minimal. If \p Separator is not in the string, then the result is a
491 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
493 /// \param Separator - The character to split on.
494 /// \return - The split substrings.
495 std::pair<StringRef, StringRef> rsplit(char Separator) const {
496 size_t Idx = rfind(Separator);
498 return std::make_pair(*this, StringRef());
499 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
502 /// Return string with consecutive characters in \p Chars starting from
503 /// the left removed.
504 StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
505 return drop_front(std::min(Length, find_first_not_of(Chars)));
508 /// Return string with consecutive characters in \p Chars starting from
509 /// the right removed.
510 StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
511 return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
514 /// Return string with consecutive characters in \p Chars starting from
515 /// the left and right removed.
516 StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
517 return ltrim(Chars).rtrim(Chars);
523 /// @name StringRef Comparison Operators
526 inline bool operator==(StringRef LHS, StringRef RHS) {
527 return LHS.equals(RHS);
530 inline bool operator!=(StringRef LHS, StringRef RHS) {
531 return !(LHS == RHS);
534 inline bool operator<(StringRef LHS, StringRef RHS) {
535 return LHS.compare(RHS) == -1;
538 inline bool operator<=(StringRef LHS, StringRef RHS) {
539 return LHS.compare(RHS) != 1;
542 inline bool operator>(StringRef LHS, StringRef RHS) {
543 return LHS.compare(RHS) == 1;
546 inline bool operator>=(StringRef LHS, StringRef RHS) {
547 return LHS.compare(RHS) != -1;
550 inline std::string &operator+=(std::string &buffer, StringRef string) {
551 return buffer.append(string.data(), string.size());
556 /// \brief Compute a hash_code for a StringRef.
557 hash_code hash_value(StringRef S);
559 // StringRefs can be treated like a POD type.
560 template <typename T> struct isPodLike;
561 template <> struct isPodLike<StringRef> { static const bool value = true; };