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/type_traits.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 PR5482: nearly all gcc 4.x miscompile StringRef and std::min()
56 // Changing the arg of min to be an integer, instead of a reference to an
57 // integer works around this bug.
58 static size_t min(size_t a, size_t b) { return a < b ? a : b; }
59 static size_t max(size_t a, size_t b) { return a > b ? a : b; }
61 // Workaround memcmp issue with null pointers (undefined behavior)
62 // by providing a specialized version
63 static int compareMemory(const char *Lhs, const char *Rhs, size_t Length) {
64 if (Length == 0) { return 0; }
65 return ::memcmp(Lhs,Rhs,Length);
69 /// @name Constructors
72 /// Construct an empty string ref.
73 /*implicit*/ StringRef() : Data(0), Length(0) {}
75 /// Construct a string ref from a cstring.
76 /*implicit*/ StringRef(const char *Str)
78 assert(Str && "StringRef cannot be built from a NULL argument");
79 Length = ::strlen(Str); // invoking strlen(NULL) is undefined behavior
82 /// Construct a string ref from a pointer and length.
83 /*implicit*/ StringRef(const char *data, size_t length)
84 : Data(data), Length(length) {
85 assert((data || length == 0) &&
86 "StringRef cannot be built from a NULL argument with non-null length");
89 /// Construct a string ref from an std::string.
90 /*implicit*/ StringRef(const std::string &Str)
91 : Data(Str.data()), Length(Str.length()) {}
93 /// Construct a string ref from a boolean.
94 explicit StringRef(bool B)
95 : Data(B ? "true" : "false"), Length(::strlen(Data)) {}
101 iterator begin() const { return Data; }
103 iterator end() const { return Data + Length; }
106 /// @name String Operations
109 /// data - Get a pointer to the start of the string (which may not be null
111 const char *data() const { return Data; }
113 /// empty - Check if the string is empty.
114 bool empty() const { return Length == 0; }
116 /// size - Get the string size.
117 size_t size() const { return Length; }
119 /// front - Get the first character in the string.
125 /// back - Get the last character in the string.
128 return Data[Length-1];
131 /// equals - Check for string equality, this is more efficient than
132 /// compare() when the relative ordering of inequal strings isn't needed.
133 bool equals(StringRef RHS) const {
134 return (Length == RHS.Length &&
135 compareMemory(Data, RHS.Data, RHS.Length) == 0);
138 /// equals_lower - Check for string equality, ignoring case.
139 bool equals_lower(StringRef RHS) const {
140 return Length == RHS.Length && compare_lower(RHS) == 0;
143 /// compare - Compare two strings; the result is -1, 0, or 1 if this string
144 /// is lexicographically less than, equal to, or greater than the \p RHS.
145 int compare(StringRef RHS) const {
146 // Check the prefix for a mismatch.
147 if (int Res = compareMemory(Data, RHS.Data, min(Length, RHS.Length)))
148 return Res < 0 ? -1 : 1;
150 // Otherwise the prefixes match, so we only need to check the lengths.
151 if (Length == RHS.Length)
153 return Length < RHS.Length ? -1 : 1;
156 /// compare_lower - Compare two strings, ignoring case.
157 int compare_lower(StringRef RHS) const;
159 /// compare_numeric - Compare two strings, treating sequences of digits as
161 int compare_numeric(StringRef RHS) const;
163 /// \brief Determine the edit distance between this string and another
166 /// \param Other the string to compare this string against.
168 /// \param AllowReplacements whether to allow character
169 /// replacements (change one character into another) as a single
170 /// operation, rather than as two operations (an insertion and a
173 /// \param MaxEditDistance If non-zero, the maximum edit distance that
174 /// this routine is allowed to compute. If the edit distance will exceed
175 /// that maximum, returns \c MaxEditDistance+1.
177 /// \returns the minimum number of character insertions, removals,
178 /// or (if \p AllowReplacements is \c true) replacements needed to
179 /// transform one of the given strings into the other. If zero,
180 /// the strings are identical.
181 unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
182 unsigned MaxEditDistance = 0);
184 /// str - Get the contents as an std::string.
185 std::string str() const {
186 if (Data == 0) return std::string();
187 return std::string(Data, Length);
191 /// @name Operator Overloads
194 char operator[](size_t Index) const {
195 assert(Index < Length && "Invalid index!");
200 /// @name Type Conversions
203 operator std::string() const {
208 /// @name String Predicates
211 /// Check if this string starts with the given \p Prefix.
212 bool startswith(StringRef Prefix) const {
213 return Length >= Prefix.Length &&
214 compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
217 /// Check if this string ends with the given \p Suffix.
218 bool endswith(StringRef Suffix) const {
219 return Length >= Suffix.Length &&
220 compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
224 /// @name String Searching
227 /// Search for the first character \p C in the string.
229 /// \returns The index of the first occurrence of \p C, or npos if not
231 size_t find(char C, size_t From = 0) const {
232 for (size_t i = min(From, Length), e = Length; i != e; ++i)
238 /// Search for the first string \p Str in the string.
240 /// \returns The index of the first occurrence of \p Str, or npos if not
242 size_t find(StringRef Str, size_t From = 0) const;
244 /// Search for the last character \p C in the string.
246 /// \returns The index of the last occurrence of \p C, or npos if not
248 size_t rfind(char C, size_t From = npos) const {
249 From = min(From, Length);
259 /// Search for the last string \p Str in the string.
261 /// \returns The index of the last occurrence of \p Str, or npos if not
263 size_t rfind(StringRef Str) const;
265 /// Find the first character in the string that is \p C, or npos if not
266 /// found. Same as find.
267 size_t find_first_of(char C, size_t From = 0) const {
268 return find(C, From);
271 /// Find the first character in the string that is in \p Chars, or npos if
274 /// Complexity: O(size() + Chars.size())
275 size_t find_first_of(StringRef Chars, size_t From = 0) const;
277 /// Find the first character in the string that is not \p C or npos if not
279 size_t find_first_not_of(char C, size_t From = 0) const;
281 /// Find the first character in the string that is not in the string
282 /// \p Chars, or npos if not found.
284 /// Complexity: O(size() + Chars.size())
285 size_t find_first_not_of(StringRef Chars, size_t From = 0) const;
287 /// Find the last character in the string that is \p C, or npos if not
289 size_t find_last_of(char C, size_t From = npos) const {
290 return rfind(C, From);
293 /// Find the last character in the string that is in \p C, or npos if not
296 /// Complexity: O(size() + Chars.size())
297 size_t find_last_of(StringRef Chars, size_t From = npos) const;
299 /// Find the last character in the string that is not \p C, or npos if not
301 size_t find_last_not_of(char C, size_t From = npos) const;
303 /// Find the last character in the string that is not in \p Chars, or
304 /// npos if not found.
306 /// Complexity: O(size() + Chars.size())
307 size_t find_last_not_of(StringRef Chars, size_t From = npos) const;
310 /// @name Helpful Algorithms
313 /// Return the number of occurrences of \p C in the string.
314 size_t count(char C) const {
316 for (size_t i = 0, e = Length; i != e; ++i)
322 /// Return the number of non-overlapped occurrences of \p Str in
324 size_t count(StringRef Str) const;
326 /// Parse the current string as an integer of the specified radix. If
327 /// \p Radix is specified as zero, this does radix autosensing using
328 /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
330 /// If the string is invalid or if only a subset of the string is valid,
331 /// this returns true to signify the error. The string is considered
332 /// erroneous if empty or if it overflows T.
333 template <typename T>
334 typename enable_if_c<std::numeric_limits<T>::is_signed, bool>::type
335 getAsInteger(unsigned Radix, T &Result) const {
337 if (getAsSignedInteger(*this, Radix, LLVal) ||
338 static_cast<T>(LLVal) != LLVal)
344 template <typename T>
345 typename enable_if_c<!std::numeric_limits<T>::is_signed, bool>::type
346 getAsInteger(unsigned Radix, T &Result) const {
347 unsigned long long ULLVal;
348 if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
349 static_cast<T>(ULLVal) != ULLVal)
355 /// Parse the current string as an integer of the specified \p Radix, or of
356 /// an autosensed radix if the \p Radix given is 0. The current value in
357 /// \p Result is discarded, and the storage is changed to be wide enough to
358 /// store the parsed integer.
360 /// \returns true if the string does not solely consist of a valid
361 /// non-empty number in the appropriate base.
363 /// APInt::fromString is superficially similar but assumes the
364 /// string is well-formed in the given radix.
365 bool getAsInteger(unsigned Radix, APInt &Result) const;
368 /// @name String Operations
371 // Convert the given ASCII string to lowercase.
372 std::string lower() const;
374 /// Convert the given ASCII string to uppercase.
375 std::string upper() const;
378 /// @name Substring Operations
381 /// Return a reference to the substring from [Start, Start + N).
383 /// \param Start The index of the starting character in the substring; if
384 /// the index is npos or greater than the length of the string then the
385 /// empty substring will be returned.
387 /// \param N The number of characters to included in the substring. If N
388 /// exceeds the number of characters remaining in the string, the string
389 /// suffix (starting with \p Start) will be returned.
390 StringRef substr(size_t Start, size_t N = npos) const {
391 Start = min(Start, Length);
392 return StringRef(Data + Start, min(N, Length - Start));
395 /// Return a StringRef equal to 'this' but with the first \p N elements
397 StringRef drop_front(size_t N = 1) const {
398 assert(size() >= N && "Dropping more elements than exist");
402 /// Return a StringRef equal to 'this' but with the last \p N elements
404 StringRef drop_back(size_t N = 1) const {
405 assert(size() >= N && "Dropping more elements than exist");
406 return substr(0, size()-N);
409 /// Return a reference to the substring from [Start, End).
411 /// \param Start The index of the starting character in the substring; if
412 /// the index is npos or greater than the length of the string then the
413 /// empty substring will be returned.
415 /// \param End The index following the last character to include in the
416 /// substring. If this is npos, or less than \p Start, or exceeds the
417 /// number of characters remaining in the string, the string suffix
418 /// (starting with \p Start) will be returned.
419 StringRef slice(size_t Start, size_t End) const {
420 Start = min(Start, Length);
421 End = min(max(Start, End), Length);
422 return StringRef(Data + Start, End - Start);
425 /// Split into two substrings around the first occurrence of a separator
428 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
429 /// such that (*this == LHS + Separator + RHS) is true and RHS is
430 /// maximal. If \p Separator is not in the string, then the result is a
431 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
433 /// \param Separator The character to split on.
434 /// \returns The split substrings.
435 std::pair<StringRef, StringRef> split(char Separator) const {
436 size_t Idx = find(Separator);
438 return std::make_pair(*this, StringRef());
439 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
442 /// Split into two substrings around the first occurrence of a separator
445 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
446 /// such that (*this == LHS + Separator + RHS) is true and RHS is
447 /// maximal. If \p Separator is not in the string, then the result is a
448 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
450 /// \param Separator - The string to split on.
451 /// \return - The split substrings.
452 std::pair<StringRef, StringRef> split(StringRef Separator) const {
453 size_t Idx = find(Separator);
455 return std::make_pair(*this, StringRef());
456 return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
459 /// Split into substrings around the occurrences of a separator string.
461 /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
462 /// \p MaxSplit splits are done and consequently <= \p MaxSplit
463 /// elements are added to A.
464 /// If \p KeepEmpty is false, empty strings are not added to \p A. They
465 /// still count when considering \p MaxSplit
466 /// An useful invariant is that
467 /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
469 /// \param A - Where to put the substrings.
470 /// \param Separator - The string to split on.
471 /// \param MaxSplit - The maximum number of times the string is split.
472 /// \param KeepEmpty - True if empty substring should be added.
473 void split(SmallVectorImpl<StringRef> &A,
474 StringRef Separator, int MaxSplit = -1,
475 bool KeepEmpty = true) const;
477 /// Split into two substrings around the last occurrence of a separator
480 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
481 /// such that (*this == LHS + Separator + RHS) is true and RHS is
482 /// minimal. If \p Separator is not in the string, then the result is a
483 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
485 /// \param Separator - The character to split on.
486 /// \return - The split substrings.
487 std::pair<StringRef, StringRef> rsplit(char Separator) const {
488 size_t Idx = rfind(Separator);
490 return std::make_pair(*this, StringRef());
491 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
494 /// Return string with consecutive characters in \p Chars starting from
495 /// the left removed.
496 StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
497 return drop_front(std::min(Length, find_first_not_of(Chars)));
500 /// Return string with consecutive characters in \p Chars starting from
501 /// the right removed.
502 StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
503 return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
506 /// Return string with consecutive characters in \p Chars starting from
507 /// the left and right removed.
508 StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
509 return ltrim(Chars).rtrim(Chars);
515 /// @name StringRef Comparison Operators
518 inline bool operator==(StringRef LHS, StringRef RHS) {
519 return LHS.equals(RHS);
522 inline bool operator!=(StringRef LHS, StringRef RHS) {
523 return !(LHS == RHS);
526 inline bool operator<(StringRef LHS, StringRef RHS) {
527 return LHS.compare(RHS) == -1;
530 inline bool operator<=(StringRef LHS, StringRef RHS) {
531 return LHS.compare(RHS) != 1;
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 std::string &operator+=(std::string &buffer, StringRef string) {
543 return buffer.append(string.data(), string.size());
548 /// \brief Compute a hash_code for a StringRef.
549 hash_code hash_value(StringRef S);
551 // StringRefs can be treated like a POD type.
552 template <typename T> struct isPodLike;
553 template <> struct isPodLike<StringRef> { static const bool value = true; };