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()) {}
97 iterator begin() const { return Data; }
99 iterator end() const { return Data + Length; }
102 /// @name String Operations
105 /// data - Get a pointer to the start of the string (which may not be null
107 const char *data() const { return Data; }
109 /// empty - Check if the string is empty.
110 bool empty() const { return Length == 0; }
112 /// size - Get the string size.
113 size_t size() const { return Length; }
115 /// front - Get the first character in the string.
121 /// back - Get the last character in the string.
124 return Data[Length-1];
127 /// equals - Check for string equality, this is more efficient than
128 /// compare() when the relative ordering of inequal strings isn't needed.
129 bool equals(StringRef RHS) const {
130 return (Length == RHS.Length &&
131 compareMemory(Data, RHS.Data, RHS.Length) == 0);
134 /// equals_lower - Check for string equality, ignoring case.
135 bool equals_lower(StringRef RHS) const {
136 return Length == RHS.Length && compare_lower(RHS) == 0;
139 /// compare - Compare two strings; the result is -1, 0, or 1 if this string
140 /// is lexicographically less than, equal to, or greater than the \arg RHS.
141 int compare(StringRef RHS) const {
142 // Check the prefix for a mismatch.
143 if (int Res = compareMemory(Data, RHS.Data, min(Length, RHS.Length)))
144 return Res < 0 ? -1 : 1;
146 // Otherwise the prefixes match, so we only need to check the lengths.
147 if (Length == RHS.Length)
149 return Length < RHS.Length ? -1 : 1;
152 /// compare_lower - Compare two strings, ignoring case.
153 int compare_lower(StringRef RHS) const;
155 /// compare_numeric - Compare two strings, treating sequences of digits as
157 int compare_numeric(StringRef RHS) const;
159 /// \brief Determine the edit distance between this string and another
162 /// \param Other the string to compare this string against.
164 /// \param AllowReplacements whether to allow character
165 /// replacements (change one character into another) as a single
166 /// operation, rather than as two operations (an insertion and a
169 /// \param MaxEditDistance If non-zero, the maximum edit distance that
170 /// this routine is allowed to compute. If the edit distance will exceed
171 /// that maximum, returns \c MaxEditDistance+1.
173 /// \returns the minimum number of character insertions, removals,
174 /// or (if \p AllowReplacements is \c true) replacements needed to
175 /// transform one of the given strings into the other. If zero,
176 /// the strings are identical.
177 unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
178 unsigned MaxEditDistance = 0);
180 /// str - Get the contents as an std::string.
181 std::string str() const {
182 if (Data == 0) return std::string();
183 return std::string(Data, Length);
187 /// @name Operator Overloads
190 char operator[](size_t Index) const {
191 assert(Index < Length && "Invalid index!");
196 /// @name Type Conversions
199 operator std::string() const {
204 /// @name String Predicates
207 /// startswith - Check if this string starts with the given \arg Prefix.
208 bool startswith(StringRef Prefix) const {
209 return Length >= Prefix.Length &&
210 compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
213 /// endswith - Check if this string ends with the given \arg Suffix.
214 bool endswith(StringRef Suffix) const {
215 return Length >= Suffix.Length &&
216 compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
220 /// @name String Searching
223 /// find - Search for the first character \arg C in the string.
225 /// \return - The index of the first occurrence of \arg C, or npos if not
227 size_t find(char C, size_t From = 0) const {
228 for (size_t i = min(From, Length), e = Length; i != e; ++i)
234 /// find - Search for the first string \arg Str in the string.
236 /// \return - The index of the first occurrence of \arg Str, or npos if not
238 size_t find(StringRef Str, size_t From = 0) const;
240 /// rfind - Search for the last character \arg C in the string.
242 /// \return - The index of the last occurrence of \arg C, or npos if not
244 size_t rfind(char C, size_t From = npos) const {
245 From = min(From, Length);
255 /// rfind - Search for the last string \arg Str in the string.
257 /// \return - The index of the last occurrence of \arg Str, or npos if not
259 size_t rfind(StringRef Str) const;
261 /// find_first_of - Find the first character in the string that is \arg C,
262 /// or npos if not found. Same as find.
263 size_type find_first_of(char C, size_t From = 0) const {
264 return find(C, From);
267 /// find_first_of - Find the first character in the string that is in \arg
268 /// Chars, or npos if not found.
270 /// Note: O(size() + Chars.size())
271 size_type find_first_of(StringRef Chars, size_t From = 0) const;
273 /// find_first_not_of - Find the first character in the string that is not
274 /// \arg C or npos if not found.
275 size_type find_first_not_of(char C, size_t From = 0) const;
277 /// find_first_not_of - Find the first character in the string that is not
278 /// in the string \arg Chars, or npos if not found.
280 /// Note: O(size() + Chars.size())
281 size_type find_first_not_of(StringRef Chars, size_t From = 0) const;
283 /// find_last_of - Find the last character in the string that is \arg C, or
284 /// npos if not found.
285 size_type find_last_of(char C, size_t From = npos) const {
286 return rfind(C, From);
289 /// find_last_of - Find the last character in the string that is in \arg C,
290 /// or npos if not found.
292 /// Note: O(size() + Chars.size())
293 size_type find_last_of(StringRef Chars, size_t From = npos) const;
295 /// find_last_not_of - Find the last character in the string that is not
296 /// \arg C, or npos if not found.
297 size_type find_last_not_of(char C, size_t From = npos) const;
299 /// find_last_not_of - Find the last character in the string that is not in
300 /// \arg Chars, or npos if not found.
302 /// Note: O(size() + Chars.size())
303 size_type find_last_not_of(StringRef Chars, size_t From = npos) const;
306 /// @name Helpful Algorithms
309 /// count - Return the number of occurrences of \arg C in the string.
310 size_t count(char C) const {
312 for (size_t i = 0, e = Length; i != e; ++i)
318 /// count - Return the number of non-overlapped occurrences of \arg Str in
320 size_t count(StringRef Str) const;
322 /// getAsInteger - Parse the current string as an integer of the specified
323 /// radix. If Radix is specified as zero, this does radix autosensing using
324 /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
326 /// If the string is invalid or if only a subset of the string is valid,
327 /// this returns true to signify the error. The string is considered
328 /// erroneous if empty or if it overflows T.
330 template <typename T>
331 typename enable_if_c<std::numeric_limits<T>::is_signed, bool>::type
332 getAsInteger(unsigned Radix, T &Result) const {
334 if (getAsSignedInteger(*this, Radix, LLVal) ||
335 static_cast<T>(LLVal) != LLVal)
341 template <typename T>
342 typename enable_if_c<!std::numeric_limits<T>::is_signed, bool>::type
343 getAsInteger(unsigned Radix, T &Result) const {
344 unsigned long long ULLVal;
345 if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
346 static_cast<T>(ULLVal) != ULLVal)
352 /// getAsInteger - Parse the current string as an integer of the
353 /// specified radix, or of an autosensed radix if the radix given
354 /// is 0. The current value in Result is discarded, and the
355 /// storage is changed to be wide enough to store the parsed
358 /// Returns true if the string does not solely consist of a valid
359 /// non-empty number in the appropriate base.
361 /// APInt::fromString is superficially similar but assumes the
362 /// string is well-formed in the given radix.
363 bool getAsInteger(unsigned Radix, APInt &Result) const;
366 /// @name String Operations
369 // lower - Convert the given ASCII string to lowercase.
370 std::string lower() const;
372 /// upper - Convert the given ASCII string to uppercase.
373 std::string upper() const;
376 /// @name Substring Operations
379 /// substr - Return a reference to the substring from [Start, Start + N).
381 /// \param Start - The index of the starting character in the substring; if
382 /// the index is npos or greater than the length of the string then the
383 /// empty substring will be returned.
385 /// \param N - The number of characters to included in the substring. If N
386 /// exceeds the number of characters remaining in the string, the string
387 /// suffix (starting with \arg Start) will be returned.
388 StringRef substr(size_t Start, size_t N = npos) const {
389 Start = min(Start, Length);
390 return StringRef(Data + Start, min(N, Length - Start));
393 /// drop_front - Return a StringRef equal to 'this' but with the first
394 /// elements dropped.
395 StringRef drop_front(unsigned N = 1) const {
396 assert(size() >= N && "Dropping more elements than exist");
400 /// drop_back - Return a StringRef equal to 'this' but with the last
401 /// elements dropped.
402 StringRef drop_back(unsigned N = 1) const {
403 assert(size() >= N && "Dropping more elements than exist");
404 return substr(0, size()-N);
407 /// slice - Return a reference to the substring from [Start, End).
409 /// \param Start - The index of the starting character in the substring; if
410 /// the index is npos or greater than the length of the string then the
411 /// empty substring will be returned.
413 /// \param End - The index following the last character to include in the
414 /// substring. If this is npos, or less than \arg Start, or exceeds the
415 /// number of characters remaining in the string, the string suffix
416 /// (starting with \arg Start) will be returned.
417 StringRef slice(size_t Start, size_t End) const {
418 Start = min(Start, Length);
419 End = min(max(Start, End), Length);
420 return StringRef(Data + Start, End - Start);
423 /// split - Split into two substrings around the first occurrence of a
424 /// separator character.
426 /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
427 /// such that (*this == LHS + Separator + RHS) is true and RHS is
428 /// maximal. If \arg Separator is not in the string, then the result is a
429 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
431 /// \param Separator - The character to split on.
432 /// \return - The split substrings.
433 std::pair<StringRef, StringRef> split(char Separator) const {
434 size_t Idx = find(Separator);
436 return std::make_pair(*this, StringRef());
437 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
440 /// split - Split into two substrings around the first occurrence of a
441 /// separator string.
443 /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
444 /// such that (*this == LHS + Separator + RHS) is true and RHS is
445 /// maximal. If \arg Separator is not in the string, then the result is a
446 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
448 /// \param Separator - The string to split on.
449 /// \return - The split substrings.
450 std::pair<StringRef, StringRef> split(StringRef Separator) const {
451 size_t Idx = find(Separator);
453 return std::make_pair(*this, StringRef());
454 return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
457 /// split - Split into substrings around the occurrences of a separator
460 /// Each substring is stored in \arg A. If \arg MaxSplit is >= 0, at most
461 /// \arg MaxSplit splits are done and consequently <= \arg MaxSplit
462 /// elements are added to A.
463 /// If \arg KeepEmpty is false, empty strings are not added to \arg A. They
464 /// still count when considering \arg MaxSplit
465 /// An useful invariant is that
466 /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
468 /// \param A - Where to put the substrings.
469 /// \param Separator - The string to split on.
470 /// \param MaxSplit - The maximum number of times the string is split.
471 /// \param KeepEmpty - True if empty substring should be added.
472 void split(SmallVectorImpl<StringRef> &A,
473 StringRef Separator, int MaxSplit = -1,
474 bool KeepEmpty = true) const;
476 /// rsplit - Split into two substrings around the last occurrence of a
477 /// separator character.
479 /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
480 /// such that (*this == LHS + Separator + RHS) is true and RHS is
481 /// minimal. If \arg Separator is not in the string, then the result is a
482 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
484 /// \param Separator - The character to split on.
485 /// \return - The split substrings.
486 std::pair<StringRef, StringRef> rsplit(char Separator) const {
487 size_t Idx = rfind(Separator);
489 return std::make_pair(*this, StringRef());
490 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
493 /// ltrim - Return string with consecutive characters in \arg Chars starting
494 /// from the left removed.
495 StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
496 return drop_front(std::min(Length, find_first_not_of(Chars)));
499 /// rtrim - Return string with consecutive characters in \arg Chars starting
500 /// from the right removed.
501 StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
502 return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
505 /// trim - Return string with consecutive characters in \arg Chars starting
506 /// from the left and right removed.
507 StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
508 return ltrim(Chars).rtrim(Chars);
514 /// @name StringRef Comparison Operators
517 inline bool operator==(StringRef LHS, StringRef RHS) {
518 return LHS.equals(RHS);
521 inline bool operator!=(StringRef LHS, StringRef RHS) {
522 return !(LHS == RHS);
525 inline bool operator<(StringRef LHS, StringRef RHS) {
526 return LHS.compare(RHS) == -1;
529 inline bool operator<=(StringRef LHS, StringRef RHS) {
530 return LHS.compare(RHS) != 1;
533 inline bool operator>(StringRef LHS, StringRef RHS) {
534 return LHS.compare(RHS) == 1;
537 inline bool operator>=(StringRef LHS, StringRef RHS) {
538 return LHS.compare(RHS) != -1;
541 inline std::string &operator+=(std::string &buffer, llvm::StringRef string) {
542 return buffer.append(string.data(), string.size());
547 /// \brief Compute a hash_code for a StringRef.
548 hash_code hash_value(StringRef S);
550 // StringRefs can be treated like a POD type.
551 template <typename T> struct isPodLike;
552 template <> struct isPodLike<StringRef> { static const bool value = true; };