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
20 class SmallVectorImpl;
24 /// StringRef - Represent a constant reference to a string, i.e. a character
25 /// array and a length, which need not be null terminated.
27 /// This class does not own the string data, it is expected to be used in
28 /// situations where the character data resides in some other buffer, whose
29 /// lifetime extends past that of the StringRef. For this reason, it is not in
30 /// general safe to store a StringRef.
33 typedef const char *iterator;
34 typedef const char *const_iterator;
35 static const size_t npos = ~size_t(0);
36 typedef size_t size_type;
39 /// The start of the string, in an external buffer.
42 /// The length of the string.
45 // Workaround PR5482: nearly all gcc 4.x miscompile StringRef and std::min()
46 // Changing the arg of min to be an integer, instead of a reference to an
47 // integer works around this bug.
48 static size_t min(size_t a, size_t b) { return a < b ? a : b; }
49 static size_t max(size_t a, size_t b) { return a > b ? a : b; }
51 // Workaround memcmp issue with null pointers (undefined behavior)
52 // by providing a specialized version
53 static int compareMemory(const char *Lhs, const char *Rhs, size_t Length) {
54 if (Length == 0) { return 0; }
55 return ::memcmp(Lhs,Rhs,Length);
59 /// @name Constructors
62 /// Construct an empty string ref.
63 /*implicit*/ StringRef() : Data(0), Length(0) {}
65 /// Construct a string ref from a cstring.
66 /*implicit*/ StringRef(const char *Str)
68 assert(Str && "StringRef cannot be built from a NULL argument");
69 Length = ::strlen(Str); // invoking strlen(NULL) is undefined behavior
72 /// Construct a string ref from a pointer and length.
73 /*implicit*/ StringRef(const char *data, size_t length)
74 : Data(data), Length(length) {
75 assert((data || length == 0) &&
76 "StringRef cannot be built from a NULL argument with non-null length");
79 /// Construct a string ref from an std::string.
80 /*implicit*/ StringRef(const std::string &Str)
81 : Data(Str.data()), Length(Str.length()) {}
87 iterator begin() const { return Data; }
89 iterator end() const { return Data + Length; }
92 /// @name String Operations
95 /// data - Get a pointer to the start of the string (which may not be null
97 const char *data() const { return Data; }
99 /// empty - Check if the string is empty.
100 bool empty() const { return Length == 0; }
102 /// size - Get the string size.
103 size_t size() const { return Length; }
105 /// front - Get the first character in the string.
111 /// back - Get the last character in the string.
114 return Data[Length-1];
117 /// equals - Check for string equality, this is more efficient than
118 /// compare() when the relative ordering of inequal strings isn't needed.
119 bool equals(StringRef RHS) const {
120 return (Length == RHS.Length &&
121 compareMemory(Data, RHS.Data, RHS.Length) == 0);
124 /// equals_lower - Check for string equality, ignoring case.
125 bool equals_lower(StringRef RHS) const {
126 return Length == RHS.Length && compare_lower(RHS) == 0;
129 /// compare - Compare two strings; the result is -1, 0, or 1 if this string
130 /// is lexicographically less than, equal to, or greater than the \arg RHS.
131 int compare(StringRef RHS) const {
132 // Check the prefix for a mismatch.
133 if (int Res = compareMemory(Data, RHS.Data, min(Length, RHS.Length)))
134 return Res < 0 ? -1 : 1;
136 // Otherwise the prefixes match, so we only need to check the lengths.
137 if (Length == RHS.Length)
139 return Length < RHS.Length ? -1 : 1;
142 /// compare_lower - Compare two strings, ignoring case.
143 int compare_lower(StringRef RHS) const;
145 /// compare_numeric - Compare two strings, treating sequences of digits as
147 int compare_numeric(StringRef RHS) const;
149 /// \brief Determine the edit distance between this string and another
152 /// \param Other the string to compare this string against.
154 /// \param AllowReplacements whether to allow character
155 /// replacements (change one character into another) as a single
156 /// operation, rather than as two operations (an insertion and a
159 /// \param MaxEditDistance If non-zero, the maximum edit distance that
160 /// this routine is allowed to compute. If the edit distance will exceed
161 /// that maximum, returns \c MaxEditDistance+1.
163 /// \returns the minimum number of character insertions, removals,
164 /// or (if \p AllowReplacements is \c true) replacements needed to
165 /// transform one of the given strings into the other. If zero,
166 /// the strings are identical.
167 unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
168 unsigned MaxEditDistance = 0);
170 /// str - Get the contents as an std::string.
171 std::string str() const {
172 if (Data == 0) return std::string();
173 return std::string(Data, Length);
177 /// @name Operator Overloads
180 char operator[](size_t Index) const {
181 assert(Index < Length && "Invalid index!");
186 /// @name Type Conversions
189 operator std::string() const {
194 /// @name String Predicates
197 /// startswith - Check if this string starts with the given \arg Prefix.
198 bool startswith(StringRef Prefix) const {
199 return Length >= Prefix.Length &&
200 compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
203 /// endswith - Check if this string ends with the given \arg Suffix.
204 bool endswith(StringRef Suffix) const {
205 return Length >= Suffix.Length &&
206 compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
210 /// @name String Searching
213 /// find - Search for the first character \arg C in the string.
215 /// \return - The index of the first occurrence of \arg C, or npos if not
217 size_t find(char C, size_t From = 0) const {
218 for (size_t i = min(From, Length), e = Length; i != e; ++i)
224 /// find - Search for the first string \arg Str in the string.
226 /// \return - The index of the first occurrence of \arg Str, or npos if not
228 size_t find(StringRef Str, size_t From = 0) const;
230 /// rfind - Search for the last character \arg C in the string.
232 /// \return - The index of the last occurrence of \arg C, or npos if not
234 size_t rfind(char C, size_t From = npos) const {
235 From = min(From, Length);
245 /// rfind - Search for the last string \arg Str in the string.
247 /// \return - The index of the last occurrence of \arg Str, or npos if not
249 size_t rfind(StringRef Str) const;
251 /// find_first_of - Find the first character in the string that is \arg C,
252 /// or npos if not found. Same as find.
253 size_type find_first_of(char C, size_t From = 0) const {
254 return find(C, From);
257 /// find_first_of - Find the first character in the string that is in \arg
258 /// Chars, or npos if not found.
260 /// Note: O(size() + Chars.size())
261 size_type find_first_of(StringRef Chars, size_t From = 0) const;
263 /// find_first_not_of - Find the first character in the string that is not
264 /// \arg C or npos if not found.
265 size_type find_first_not_of(char C, size_t From = 0) const;
267 /// find_first_not_of - Find the first character in the string that is not
268 /// in the string \arg Chars, or npos if not found.
270 /// Note: O(size() + Chars.size())
271 size_type find_first_not_of(StringRef Chars, size_t From = 0) const;
273 /// find_last_of - Find the last character in the string that is \arg C, or
274 /// npos if not found.
275 size_type find_last_of(char C, size_t From = npos) const {
276 return rfind(C, From);
279 /// find_last_of - Find the last character in the string that is in \arg C,
280 /// or npos if not found.
282 /// Note: O(size() + Chars.size())
283 size_type find_last_of(StringRef Chars, size_t From = npos) const;
286 /// @name Helpful Algorithms
289 /// count - Return the number of occurrences of \arg C in the string.
290 size_t count(char C) const {
292 for (size_t i = 0, e = Length; i != e; ++i)
298 /// count - Return the number of non-overlapped occurrences of \arg Str in
300 size_t count(StringRef Str) const;
302 /// getAsInteger - Parse the current string as an integer of the specified
303 /// radix. If Radix is specified as zero, this does radix autosensing using
304 /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
306 /// If the string is invalid or if only a subset of the string is valid,
307 /// this returns true to signify the error. The string is considered
308 /// erroneous if empty.
310 bool getAsInteger(unsigned Radix, long long &Result) const;
311 bool getAsInteger(unsigned Radix, unsigned long long &Result) const;
312 bool getAsInteger(unsigned Radix, int &Result) const;
313 bool getAsInteger(unsigned Radix, unsigned &Result) const;
315 // TODO: Provide overloads for int/unsigned that check for overflow.
317 /// getAsInteger - Parse the current string as an integer of the
318 /// specified radix, or of an autosensed radix if the radix given
319 /// is 0. The current value in Result is discarded, and the
320 /// storage is changed to be wide enough to store the parsed
323 /// Returns true if the string does not solely consist of a valid
324 /// non-empty number in the appropriate base.
326 /// APInt::fromString is superficially similar but assumes the
327 /// string is well-formed in the given radix.
328 bool getAsInteger(unsigned Radix, APInt &Result) const;
331 /// @name String Operations
334 // lower - Convert the given ASCII string to lowercase.
335 std::string lower() const;
337 /// upper - Convert the given ASCII string to uppercase.
338 std::string upper() const;
341 /// @name Substring Operations
344 /// substr - Return a reference to the substring from [Start, Start + N).
346 /// \param Start - The index of the starting character in the substring; if
347 /// the index is npos or greater than the length of the string then the
348 /// empty substring will be returned.
350 /// \param N - The number of characters to included in the substring. If N
351 /// exceeds the number of characters remaining in the string, the string
352 /// suffix (starting with \arg Start) will be returned.
353 StringRef substr(size_t Start, size_t N = npos) const {
354 Start = min(Start, Length);
355 return StringRef(Data + Start, min(N, Length - Start));
358 /// drop_front - Return a StringRef equal to 'this' but with the first
359 /// elements dropped.
360 StringRef drop_front(unsigned N = 1) const {
361 assert(size() >= N && "Dropping more elements than exist");
365 /// drop_back - Return a StringRef equal to 'this' but with the last
366 /// elements dropped.
367 StringRef drop_back(unsigned N = 1) const {
368 assert(size() >= N && "Dropping more elements than exist");
369 return substr(0, size()-N);
372 /// slice - Return a reference to the substring from [Start, End).
374 /// \param Start - The index of the starting character in the substring; if
375 /// the index is npos or greater than the length of the string then the
376 /// empty substring will be returned.
378 /// \param End - The index following the last character to include in the
379 /// substring. If this is npos, or less than \arg Start, or exceeds the
380 /// number of characters remaining in the string, the string suffix
381 /// (starting with \arg Start) will be returned.
382 StringRef slice(size_t Start, size_t End) const {
383 Start = min(Start, Length);
384 End = min(max(Start, End), Length);
385 return StringRef(Data + Start, End - Start);
388 /// split - Split into two substrings around the first occurrence of a
389 /// separator character.
391 /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
392 /// such that (*this == LHS + Separator + RHS) is true and RHS is
393 /// maximal. If \arg Separator is not in the string, then the result is a
394 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
396 /// \param Separator - The character to split on.
397 /// \return - The split substrings.
398 std::pair<StringRef, StringRef> split(char Separator) const {
399 size_t Idx = find(Separator);
401 return std::make_pair(*this, StringRef());
402 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
405 /// split - Split into two substrings around the first occurrence of a
406 /// separator string.
408 /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
409 /// such that (*this == LHS + Separator + RHS) is true and RHS is
410 /// maximal. If \arg Separator is not in the string, then the result is a
411 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
413 /// \param Separator - The string to split on.
414 /// \return - The split substrings.
415 std::pair<StringRef, StringRef> split(StringRef Separator) const {
416 size_t Idx = find(Separator);
418 return std::make_pair(*this, StringRef());
419 return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
422 /// split - Split into substrings around the occurrences of a separator
425 /// Each substring is stored in \arg A. If \arg MaxSplit is >= 0, at most
426 /// \arg MaxSplit splits are done and consequently <= \arg MaxSplit
427 /// elements are added to A.
428 /// If \arg KeepEmpty is false, empty strings are not added to \arg A. They
429 /// still count when considering \arg MaxSplit
430 /// An useful invariant is that
431 /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
433 /// \param A - Where to put the substrings.
434 /// \param Separator - The string to split on.
435 /// \param MaxSplit - The maximum number of times the string is split.
436 /// \param KeepEmpty - True if empty substring should be added.
437 void split(SmallVectorImpl<StringRef> &A,
438 StringRef Separator, int MaxSplit = -1,
439 bool KeepEmpty = true) const;
441 /// rsplit - Split into two substrings around the last occurrence of a
442 /// separator character.
444 /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
445 /// such that (*this == LHS + Separator + RHS) is true and RHS is
446 /// minimal. If \arg Separator is not in the string, then the result is a
447 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
449 /// \param Separator - The character to split on.
450 /// \return - The split substrings.
451 std::pair<StringRef, StringRef> rsplit(char Separator) const {
452 size_t Idx = rfind(Separator);
454 return std::make_pair(*this, StringRef());
455 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
461 /// @name StringRef Comparison Operators
464 inline bool operator==(StringRef LHS, StringRef RHS) {
465 return LHS.equals(RHS);
468 inline bool operator!=(StringRef LHS, StringRef RHS) {
469 return !(LHS == RHS);
472 inline bool operator<(StringRef LHS, StringRef RHS) {
473 return LHS.compare(RHS) == -1;
476 inline bool operator<=(StringRef LHS, StringRef RHS) {
477 return LHS.compare(RHS) != 1;
480 inline bool operator>(StringRef LHS, StringRef RHS) {
481 return LHS.compare(RHS) == 1;
484 inline bool operator>=(StringRef LHS, StringRef RHS) {
485 return LHS.compare(RHS) != -1;
488 inline std::string &operator+=(std::string &buffer, llvm::StringRef string) {
489 return buffer.append(string.data(), string.size());
494 /// \brief Compute a hash_code for a StringRef.
495 hash_code hash_value(StringRef S);
497 // StringRefs can be treated like a POD type.
498 template <typename T> struct isPodLike;
499 template <> struct isPodLike<StringRef> { static const bool value = true; };