]>
git.proxmox.com Git - rustc.git/blob - src/llvm/include/llvm/ADT/StringRef.h
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"
24 class SmallVectorImpl
;
29 /// Helper functions for StringRef::getAsInteger.
30 bool getAsUnsignedInteger(StringRef Str
, unsigned Radix
,
31 unsigned long long &Result
);
33 bool getAsSignedInteger(StringRef Str
, unsigned Radix
, long long &Result
);
35 /// StringRef - Represent a constant reference to a string, i.e. a character
36 /// array and a length, which need not be null terminated.
38 /// This class does not own the string data, it is expected to be used in
39 /// situations where the character data resides in some other buffer, whose
40 /// lifetime extends past that of the StringRef. For this reason, it is not in
41 /// general safe to store a StringRef.
44 typedef const char *iterator
;
45 typedef const char *const_iterator
;
46 static const size_t npos
= ~size_t(0);
47 typedef size_t size_type
;
50 /// The start of the string, in an external buffer.
53 /// The length of the string.
56 // Workaround PR5482: nearly all gcc 4.x miscompile StringRef and std::min()
57 // Changing the arg of min to be an integer, instead of a reference to an
58 // integer works around this bug.
59 static size_t min(size_t a
, size_t b
) { return a
< b
? a
: b
; }
60 static size_t max(size_t a
, size_t b
) { return a
> b
? a
: b
; }
62 // Workaround memcmp issue with null pointers (undefined behavior)
63 // by providing a specialized version
64 static int compareMemory(const char *Lhs
, const char *Rhs
, size_t Length
) {
65 if (Length
== 0) { return 0; }
66 return ::memcmp(Lhs
,Rhs
,Length
);
70 /// @name Constructors
73 /// Construct an empty string ref.
74 /*implicit*/ StringRef() : Data(0), Length(0) {}
76 /// Construct a string ref from a cstring.
77 /*implicit*/ StringRef(const char *Str
)
79 assert(Str
&& "StringRef cannot be built from a NULL argument");
80 Length
= ::strlen(Str
); // invoking strlen(NULL) is undefined behavior
83 /// Construct a string ref from a pointer and length.
84 /*implicit*/ StringRef(const char *data
, size_t length
)
85 : Data(data
), Length(length
) {
86 assert((data
|| length
== 0) &&
87 "StringRef cannot be built from a NULL argument with non-null length");
90 /// Construct a string ref from an std::string.
91 /*implicit*/ StringRef(const std::string
&Str
)
92 : Data(Str
.data()), Length(Str
.length()) {}
98 iterator
begin() const { return Data
; }
100 iterator
end() const { return Data
+ Length
; }
103 /// @name String Operations
106 /// data - Get a pointer to the start of the string (which may not be null
108 const char *data() const { return Data
; }
110 /// empty - Check if the string is empty.
111 bool empty() const { return Length
== 0; }
113 /// size - Get the string size.
114 size_t size() const { return Length
; }
116 /// front - Get the first character in the string.
122 /// back - Get the last character in the string.
125 return Data
[Length
-1];
128 /// equals - Check for string equality, this is more efficient than
129 /// compare() when the relative ordering of inequal strings isn't needed.
130 bool equals(StringRef RHS
) const {
131 return (Length
== RHS
.Length
&&
132 compareMemory(Data
, RHS
.Data
, RHS
.Length
) == 0);
135 /// equals_lower - Check for string equality, ignoring case.
136 bool equals_lower(StringRef RHS
) const {
137 return Length
== RHS
.Length
&& compare_lower(RHS
) == 0;
140 /// compare - Compare two strings; the result is -1, 0, or 1 if this string
141 /// is lexicographically less than, equal to, or greater than the \p RHS.
142 int compare(StringRef RHS
) const {
143 // Check the prefix for a mismatch.
144 if (int Res
= compareMemory(Data
, RHS
.Data
, min(Length
, RHS
.Length
)))
145 return Res
< 0 ? -1 : 1;
147 // Otherwise the prefixes match, so we only need to check the lengths.
148 if (Length
== RHS
.Length
)
150 return Length
< RHS
.Length
? -1 : 1;
153 /// compare_lower - Compare two strings, ignoring case.
154 int compare_lower(StringRef RHS
) const;
156 /// compare_numeric - Compare two strings, treating sequences of digits as
158 int compare_numeric(StringRef RHS
) const;
160 /// \brief Determine the edit distance between this string and another
163 /// \param Other the string to compare this string against.
165 /// \param AllowReplacements whether to allow character
166 /// replacements (change one character into another) as a single
167 /// operation, rather than as two operations (an insertion and a
170 /// \param MaxEditDistance If non-zero, the maximum edit distance that
171 /// this routine is allowed to compute. If the edit distance will exceed
172 /// that maximum, returns \c MaxEditDistance+1.
174 /// \returns the minimum number of character insertions, removals,
175 /// or (if \p AllowReplacements is \c true) replacements needed to
176 /// transform one of the given strings into the other. If zero,
177 /// the strings are identical.
178 unsigned edit_distance(StringRef Other
, bool AllowReplacements
= true,
179 unsigned MaxEditDistance
= 0);
181 /// str - Get the contents as an std::string.
182 std::string
str() const {
183 if (Data
== 0) return std::string();
184 return std::string(Data
, Length
);
188 /// @name Operator Overloads
191 char operator[](size_t Index
) const {
192 assert(Index
< Length
&& "Invalid index!");
197 /// @name Type Conversions
200 operator std::string() const {
205 /// @name String Predicates
208 /// Check if this string starts with the given \p Prefix.
209 bool startswith(StringRef Prefix
) const {
210 return Length
>= Prefix
.Length
&&
211 compareMemory(Data
, Prefix
.Data
, Prefix
.Length
) == 0;
214 /// Check if this string ends with the given \p Suffix.
215 bool endswith(StringRef Suffix
) const {
216 return Length
>= Suffix
.Length
&&
217 compareMemory(end() - Suffix
.Length
, Suffix
.Data
, Suffix
.Length
) == 0;
221 /// @name String Searching
224 /// Search for the first character \p C in the string.
226 /// \returns The index of the first occurrence of \p C, or npos if not
228 size_t find(char C
, size_t From
= 0) const {
229 for (size_t i
= min(From
, Length
), e
= Length
; i
!= e
; ++i
)
235 /// Search for the first string \p Str in the string.
237 /// \returns The index of the first occurrence of \p Str, or npos if not
239 size_t find(StringRef Str
, size_t From
= 0) const;
241 /// Search for the last character \p C in the string.
243 /// \returns The index of the last occurrence of \p C, or npos if not
245 size_t rfind(char C
, size_t From
= npos
) const {
246 From
= min(From
, Length
);
256 /// Search for the last string \p Str in the string.
258 /// \returns The index of the last occurrence of \p Str, or npos if not
260 size_t rfind(StringRef Str
) const;
262 /// Find the first character in the string that is \p C, or npos if not
263 /// found. Same as find.
264 size_type
find_first_of(char C
, size_t From
= 0) const {
265 return find(C
, From
);
268 /// Find the first character in the string that is in \p Chars, or npos if
271 /// Complexity: O(size() + Chars.size())
272 size_type
find_first_of(StringRef Chars
, size_t From
= 0) const;
274 /// Find the first character in the string that is not \p C or npos if not
276 size_type
find_first_not_of(char C
, size_t From
= 0) const;
278 /// Find the first character in the string that is not in the string
279 /// \p Chars, or npos if not found.
281 /// Complexity: O(size() + Chars.size())
282 size_type
find_first_not_of(StringRef Chars
, size_t From
= 0) const;
284 /// Find the last character in the string that is \p C, or npos if not
286 size_type
find_last_of(char C
, size_t From
= npos
) const {
287 return rfind(C
, From
);
290 /// Find the last character in the string that is in \p C, or npos if not
293 /// Complexity: O(size() + Chars.size())
294 size_type
find_last_of(StringRef Chars
, size_t From
= npos
) const;
296 /// Find the last character in the string that is not \p C, or npos if not
298 size_type
find_last_not_of(char C
, size_t From
= npos
) const;
300 /// Find the last character in the string that is not in \p Chars, or
301 /// npos if not found.
303 /// Complexity: O(size() + Chars.size())
304 size_type
find_last_not_of(StringRef Chars
, size_t From
= npos
) const;
307 /// @name Helpful Algorithms
310 /// Return the number of occurrences of \p C in the string.
311 size_t count(char C
) const {
313 for (size_t i
= 0, e
= Length
; i
!= e
; ++i
)
319 /// Return the number of non-overlapped occurrences of \p Str in
321 size_t count(StringRef Str
) const;
323 /// Parse the current string as an integer of the specified radix. If
324 /// \p Radix is specified as zero, this does radix autosensing using
325 /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
327 /// If the string is invalid or if only a subset of the string is valid,
328 /// this returns true to signify the error. The string is considered
329 /// 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 /// Parse the current string as an integer of the specified \p Radix, or of
353 /// an autosensed radix if the \p Radix given is 0. The current value in
354 /// \p Result is discarded, and the storage is changed to be wide enough to
355 /// store the parsed integer.
357 /// \returns true if the string does not solely consist of a valid
358 /// non-empty number in the appropriate base.
360 /// APInt::fromString is superficially similar but assumes the
361 /// string is well-formed in the given radix.
362 bool getAsInteger(unsigned Radix
, APInt
&Result
) const;
365 /// @name String Operations
368 // Convert the given ASCII string to lowercase.
369 std::string
lower() const;
371 /// Convert the given ASCII string to uppercase.
372 std::string
upper() const;
375 /// @name Substring Operations
378 /// Return a reference to the substring from [Start, Start + N).
380 /// \param Start The index of the starting character in the substring; if
381 /// the index is npos or greater than the length of the string then the
382 /// empty substring will be returned.
384 /// \param N The number of characters to included in the substring. If N
385 /// exceeds the number of characters remaining in the string, the string
386 /// suffix (starting with \p Start) will be returned.
387 StringRef
substr(size_t Start
, size_t N
= npos
) const {
388 Start
= min(Start
, Length
);
389 return StringRef(Data
+ Start
, min(N
, Length
- Start
));
392 /// Return a StringRef equal to 'this' but with the first \p N elements
394 StringRef
drop_front(unsigned N
= 1) const {
395 assert(size() >= N
&& "Dropping more elements than exist");
399 /// Return a StringRef equal to 'this' but with the last \p N elements
401 StringRef
drop_back(unsigned N
= 1) const {
402 assert(size() >= N
&& "Dropping more elements than exist");
403 return substr(0, size()-N
);
406 /// Return a reference to the substring from [Start, End).
408 /// \param Start The index of the starting character in the substring; if
409 /// the index is npos or greater than the length of the string then the
410 /// empty substring will be returned.
412 /// \param End The index following the last character to include in the
413 /// substring. If this is npos, or less than \p Start, or exceeds the
414 /// number of characters remaining in the string, the string suffix
415 /// (starting with \p Start) will be returned.
416 StringRef
slice(size_t Start
, size_t End
) const {
417 Start
= min(Start
, Length
);
418 End
= min(max(Start
, End
), Length
);
419 return StringRef(Data
+ Start
, End
- Start
);
422 /// Split into two substrings around the first occurrence of a separator
425 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
426 /// such that (*this == LHS + Separator + RHS) is true and RHS is
427 /// maximal. If \p Separator is not in the string, then the result is a
428 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
430 /// \param Separator The character to split on.
431 /// \returns The split substrings.
432 std::pair
<StringRef
, StringRef
> split(char Separator
) const {
433 size_t Idx
= find(Separator
);
435 return std::make_pair(*this, StringRef());
436 return std::make_pair(slice(0, Idx
), slice(Idx
+1, npos
));
439 /// Split into two substrings around the first occurrence of a separator
442 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
443 /// such that (*this == LHS + Separator + RHS) is true and RHS is
444 /// maximal. If \p Separator is not in the string, then the result is a
445 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
447 /// \param Separator - The string to split on.
448 /// \return - The split substrings.
449 std::pair
<StringRef
, StringRef
> split(StringRef Separator
) const {
450 size_t Idx
= find(Separator
);
452 return std::make_pair(*this, StringRef());
453 return std::make_pair(slice(0, Idx
), slice(Idx
+ Separator
.size(), npos
));
456 /// Split into substrings around the occurrences of a separator string.
458 /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
459 /// \p MaxSplit splits are done and consequently <= \p MaxSplit
460 /// elements are added to A.
461 /// If \p KeepEmpty is false, empty strings are not added to \p A. They
462 /// still count when considering \p MaxSplit
463 /// An useful invariant is that
464 /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
466 /// \param A - Where to put the substrings.
467 /// \param Separator - The string to split on.
468 /// \param MaxSplit - The maximum number of times the string is split.
469 /// \param KeepEmpty - True if empty substring should be added.
470 void split(SmallVectorImpl
<StringRef
> &A
,
471 StringRef Separator
, int MaxSplit
= -1,
472 bool KeepEmpty
= true) const;
474 /// Split into two substrings around the last occurrence of a separator
477 /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
478 /// such that (*this == LHS + Separator + RHS) is true and RHS is
479 /// minimal. If \p Separator is not in the string, then the result is a
480 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
482 /// \param Separator - The character to split on.
483 /// \return - The split substrings.
484 std::pair
<StringRef
, StringRef
> rsplit(char Separator
) const {
485 size_t Idx
= rfind(Separator
);
487 return std::make_pair(*this, StringRef());
488 return std::make_pair(slice(0, Idx
), slice(Idx
+1, npos
));
491 /// Return string with consecutive characters in \p Chars starting from
492 /// the left removed.
493 StringRef
ltrim(StringRef Chars
= " \t\n\v\f\r") const {
494 return drop_front(std::min(Length
, find_first_not_of(Chars
)));
497 /// Return string with consecutive characters in \p Chars starting from
498 /// the right removed.
499 StringRef
rtrim(StringRef Chars
= " \t\n\v\f\r") const {
500 return drop_back(Length
- std::min(Length
, find_last_not_of(Chars
) + 1));
503 /// Return string with consecutive characters in \p Chars starting from
504 /// the left and right removed.
505 StringRef
trim(StringRef Chars
= " \t\n\v\f\r") const {
506 return ltrim(Chars
).rtrim(Chars
);
512 /// @name StringRef Comparison Operators
515 inline bool operator==(StringRef LHS
, StringRef RHS
) {
516 return LHS
.equals(RHS
);
519 inline bool operator!=(StringRef LHS
, StringRef RHS
) {
520 return !(LHS
== RHS
);
523 inline bool operator<(StringRef LHS
, StringRef RHS
) {
524 return LHS
.compare(RHS
) == -1;
527 inline bool operator<=(StringRef LHS
, StringRef RHS
) {
528 return LHS
.compare(RHS
) != 1;
531 inline bool operator>(StringRef LHS
, StringRef RHS
) {
532 return LHS
.compare(RHS
) == 1;
535 inline bool operator>=(StringRef LHS
, StringRef RHS
) {
536 return LHS
.compare(RHS
) != -1;
539 inline std::string
&operator+=(std::string
&buffer
, llvm::StringRef string
) {
540 return buffer
.append(string
.data(), string
.size());
545 /// \brief Compute a hash_code for a StringRef.
546 hash_code
hash_value(StringRef S
);
548 // StringRefs can be treated like a POD type.
549 template <typename T
> struct isPodLike
;
550 template <> struct isPodLike
<StringRef
> { static const bool value
= true; };