Add back some typecasts I accidentally lost in r206142.
[oota-llvm.git] / include / llvm / ADT / StringRef.h
1 //===--- StringRef.h - Constant String Reference Wrapper --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_ADT_STRINGREF_H
11 #define LLVM_ADT_STRINGREF_H
12
13 #include "llvm/Support/Allocator.h"
14 #include <algorithm>
15 #include <cassert>
16 #include <cstring>
17 #include <limits>
18 #include <string>
19 #include <utility>
20
21 namespace llvm {
22   template <typename T>
23   class SmallVectorImpl;
24   class APInt;
25   class hash_code;
26   class StringRef;
27
28   /// Helper functions for StringRef::getAsInteger.
29   bool getAsUnsignedInteger(StringRef Str, unsigned Radix,
30                             unsigned long long &Result);
31
32   bool getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result);
33
34   /// StringRef - Represent a constant reference to a string, i.e. a character
35   /// array and a length, which need not be null terminated.
36   ///
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.
41   class StringRef {
42   public:
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;
47
48   private:
49     /// The start of the string, in an external buffer.
50     const char *Data;
51
52     /// The length of the string.
53     size_t Length;
54
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; }
60
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);
66     }
67
68   public:
69     /// @name Constructors
70     /// @{
71
72     /// Construct an empty string ref.
73     /*implicit*/ StringRef() : Data(nullptr), Length(0) {}
74
75     /// Construct a string ref from a cstring.
76     /*implicit*/ StringRef(const char *Str)
77       : Data(Str) {
78         assert(Str && "StringRef cannot be built from a NULL argument");
79         Length = ::strlen(Str); // invoking strlen(NULL) is undefined behavior
80       }
81
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");
87       }
88
89     /// Construct a string ref from an std::string.
90     /*implicit*/ StringRef(const std::string &Str)
91       : Data(Str.data()), Length(Str.length()) {}
92
93     /// @}
94     /// @name Iterators
95     /// @{
96
97     iterator begin() const { return Data; }
98
99     iterator end() const { return Data + Length; }
100
101     /// @}
102     /// @name String Operations
103     /// @{
104
105     /// data - Get a pointer to the start of the string (which may not be null
106     /// terminated).
107     const char *data() const { return Data; }
108
109     /// empty - Check if the string is empty.
110     bool empty() const { return Length == 0; }
111
112     /// size - Get the string size.
113     size_t size() const { return Length; }
114
115     /// front - Get the first character in the string.
116     char front() const {
117       assert(!empty());
118       return Data[0];
119     }
120
121     /// back - Get the last character in the string.
122     char back() const {
123       assert(!empty());
124       return Data[Length-1];
125     }
126
127     // copy - Allocate copy in BumpPtrAllocator and return StringRef to it.
128     StringRef copy(BumpPtrAllocator &Allocator) {
129       char *S = Allocator.Allocate<char>(Length);
130       std::copy(begin(), end(), S);
131       return StringRef(S, Length);
132     }
133
134     /// equals - Check for string equality, this is more efficient than
135     /// compare() when the relative ordering of inequal strings isn't needed.
136     bool equals(StringRef RHS) const {
137       return (Length == RHS.Length &&
138               compareMemory(Data, RHS.Data, RHS.Length) == 0);
139     }
140
141     /// equals_lower - Check for string equality, ignoring case.
142     bool equals_lower(StringRef RHS) const {
143       return Length == RHS.Length && compare_lower(RHS) == 0;
144     }
145
146     /// compare - Compare two strings; the result is -1, 0, or 1 if this string
147     /// is lexicographically less than, equal to, or greater than the \p RHS.
148     int compare(StringRef RHS) const {
149       // Check the prefix for a mismatch.
150       if (int Res = compareMemory(Data, RHS.Data, min(Length, RHS.Length)))
151         return Res < 0 ? -1 : 1;
152
153       // Otherwise the prefixes match, so we only need to check the lengths.
154       if (Length == RHS.Length)
155         return 0;
156       return Length < RHS.Length ? -1 : 1;
157     }
158
159     /// compare_lower - Compare two strings, ignoring case.
160     int compare_lower(StringRef RHS) const;
161
162     /// compare_numeric - Compare two strings, treating sequences of digits as
163     /// numbers.
164     int compare_numeric(StringRef RHS) const;
165
166     /// \brief Determine the edit distance between this string and another
167     /// string.
168     ///
169     /// \param Other the string to compare this string against.
170     ///
171     /// \param AllowReplacements whether to allow character
172     /// replacements (change one character into another) as a single
173     /// operation, rather than as two operations (an insertion and a
174     /// removal).
175     ///
176     /// \param MaxEditDistance If non-zero, the maximum edit distance that
177     /// this routine is allowed to compute. If the edit distance will exceed
178     /// that maximum, returns \c MaxEditDistance+1.
179     ///
180     /// \returns the minimum number of character insertions, removals,
181     /// or (if \p AllowReplacements is \c true) replacements needed to
182     /// transform one of the given strings into the other. If zero,
183     /// the strings are identical.
184     unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
185                            unsigned MaxEditDistance = 0) const;
186
187     /// str - Get the contents as an std::string.
188     std::string str() const {
189       if (!Data) return std::string();
190       return std::string(Data, Length);
191     }
192
193     /// @}
194     /// @name Operator Overloads
195     /// @{
196
197     char operator[](size_t Index) const {
198       assert(Index < Length && "Invalid index!");
199       return Data[Index];
200     }
201
202     /// @}
203     /// @name Type Conversions
204     /// @{
205
206     operator std::string() const {
207       return str();
208     }
209
210     /// @}
211     /// @name String Predicates
212     /// @{
213
214     /// Check if this string starts with the given \p Prefix.
215     bool startswith(StringRef Prefix) const {
216       return Length >= Prefix.Length &&
217              compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
218     }
219
220     /// Check if this string starts with the given \p Prefix, ignoring case.
221     bool startswith_lower(StringRef Prefix) const;
222
223     /// Check if this string ends with the given \p Suffix.
224     bool endswith(StringRef Suffix) const {
225       return Length >= Suffix.Length &&
226         compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
227     }
228
229     /// Check if this string ends with the given \p Suffix, ignoring case.
230     bool endswith_lower(StringRef Suffix) const;
231
232     /// @}
233     /// @name String Searching
234     /// @{
235
236     /// Search for the first character \p C in the string.
237     ///
238     /// \returns The index of the first occurrence of \p C, or npos if not
239     /// found.
240     size_t find(char C, size_t From = 0) const {
241       for (size_t i = min(From, Length), e = Length; i != e; ++i)
242         if (Data[i] == C)
243           return i;
244       return npos;
245     }
246
247     /// Search for the first string \p Str in the string.
248     ///
249     /// \returns The index of the first occurrence of \p Str, or npos if not
250     /// found.
251     size_t find(StringRef Str, size_t From = 0) const;
252
253     /// Search for the last character \p C in the string.
254     ///
255     /// \returns The index of the last occurrence of \p C, or npos if not
256     /// found.
257     size_t rfind(char C, size_t From = npos) const {
258       From = min(From, Length);
259       size_t i = From;
260       while (i != 0) {
261         --i;
262         if (Data[i] == C)
263           return i;
264       }
265       return npos;
266     }
267
268     /// Search for the last string \p Str in the string.
269     ///
270     /// \returns The index of the last occurrence of \p Str, or npos if not
271     /// found.
272     size_t rfind(StringRef Str) const;
273
274     /// Find the first character in the string that is \p C, or npos if not
275     /// found. Same as find.
276     size_t find_first_of(char C, size_t From = 0) const {
277       return find(C, From);
278     }
279
280     /// Find the first character in the string that is in \p Chars, or npos if
281     /// not found.
282     ///
283     /// Complexity: O(size() + Chars.size())
284     size_t find_first_of(StringRef Chars, size_t From = 0) const;
285
286     /// Find the first character in the string that is not \p C or npos if not
287     /// found.
288     size_t find_first_not_of(char C, size_t From = 0) const;
289
290     /// Find the first character in the string that is not in the string
291     /// \p Chars, or npos if not found.
292     ///
293     /// Complexity: O(size() + Chars.size())
294     size_t find_first_not_of(StringRef Chars, size_t From = 0) const;
295
296     /// Find the last character in the string that is \p C, or npos if not
297     /// found.
298     size_t find_last_of(char C, size_t From = npos) const {
299       return rfind(C, From);
300     }
301
302     /// Find the last character in the string that is in \p C, or npos if not
303     /// found.
304     ///
305     /// Complexity: O(size() + Chars.size())
306     size_t find_last_of(StringRef Chars, size_t From = npos) const;
307
308     /// Find the last character in the string that is not \p C, or npos if not
309     /// found.
310     size_t find_last_not_of(char C, size_t From = npos) const;
311
312     /// Find the last character in the string that is not in \p Chars, or
313     /// npos if not found.
314     ///
315     /// Complexity: O(size() + Chars.size())
316     size_t find_last_not_of(StringRef Chars, size_t From = npos) const;
317
318     /// @}
319     /// @name Helpful Algorithms
320     /// @{
321
322     /// Return the number of occurrences of \p C in the string.
323     size_t count(char C) const {
324       size_t Count = 0;
325       for (size_t i = 0, e = Length; i != e; ++i)
326         if (Data[i] == C)
327           ++Count;
328       return Count;
329     }
330
331     /// Return the number of non-overlapped occurrences of \p Str in
332     /// the string.
333     size_t count(StringRef Str) const;
334
335     /// Parse the current string as an integer of the specified radix.  If
336     /// \p Radix is specified as zero, this does radix autosensing using
337     /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
338     ///
339     /// If the string is invalid or if only a subset of the string is valid,
340     /// this returns true to signify the error.  The string is considered
341     /// erroneous if empty or if it overflows T.
342     template <typename T>
343     typename std::enable_if<std::numeric_limits<T>::is_signed, bool>::type
344     getAsInteger(unsigned Radix, T &Result) const {
345       long long LLVal;
346       if (getAsSignedInteger(*this, Radix, LLVal) ||
347             static_cast<T>(LLVal) != LLVal)
348         return true;
349       Result = LLVal;
350       return false;
351     }
352
353     template <typename T>
354     typename std::enable_if<!std::numeric_limits<T>::is_signed, bool>::type
355     getAsInteger(unsigned Radix, T &Result) const {
356       unsigned long long ULLVal;
357       if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
358             static_cast<T>(ULLVal) != ULLVal)
359         return true;
360       Result = ULLVal;
361       return false;
362     }
363
364     /// Parse the current string as an integer of the specified \p Radix, or of
365     /// an autosensed radix if the \p Radix given is 0.  The current value in
366     /// \p Result is discarded, and the storage is changed to be wide enough to
367     /// store the parsed integer.
368     ///
369     /// \returns true if the string does not solely consist of a valid
370     /// non-empty number in the appropriate base.
371     ///
372     /// APInt::fromString is superficially similar but assumes the
373     /// string is well-formed in the given radix.
374     bool getAsInteger(unsigned Radix, APInt &Result) const;
375
376     /// @}
377     /// @name String Operations
378     /// @{
379
380     // Convert the given ASCII string to lowercase.
381     std::string lower() const;
382
383     /// Convert the given ASCII string to uppercase.
384     std::string upper() const;
385
386     /// @}
387     /// @name Substring Operations
388     /// @{
389
390     /// Return a reference to the substring from [Start, Start + N).
391     ///
392     /// \param Start The index of the starting character in the substring; if
393     /// the index is npos or greater than the length of the string then the
394     /// empty substring will be returned.
395     ///
396     /// \param N The number of characters to included in the substring. If N
397     /// exceeds the number of characters remaining in the string, the string
398     /// suffix (starting with \p Start) will be returned.
399     StringRef substr(size_t Start, size_t N = npos) const {
400       Start = min(Start, Length);
401       return StringRef(Data + Start, min(N, Length - Start));
402     }
403
404     /// Return a StringRef equal to 'this' but with the first \p N elements
405     /// dropped.
406     StringRef drop_front(size_t N = 1) const {
407       assert(size() >= N && "Dropping more elements than exist");
408       return substr(N);
409     }
410
411     /// Return a StringRef equal to 'this' but with the last \p N elements
412     /// dropped.
413     StringRef drop_back(size_t N = 1) const {
414       assert(size() >= N && "Dropping more elements than exist");
415       return substr(0, size()-N);
416     }
417
418     /// Return a reference to the substring from [Start, End).
419     ///
420     /// \param Start The index of the starting character in the substring; if
421     /// the index is npos or greater than the length of the string then the
422     /// empty substring will be returned.
423     ///
424     /// \param End The index following the last character to include in the
425     /// substring. If this is npos, or less than \p Start, or exceeds the
426     /// number of characters remaining in the string, the string suffix
427     /// (starting with \p Start) will be returned.
428     StringRef slice(size_t Start, size_t End) const {
429       Start = min(Start, Length);
430       End = min(max(Start, End), Length);
431       return StringRef(Data + Start, End - Start);
432     }
433
434     /// Split into two substrings around the first occurrence of a separator
435     /// character.
436     ///
437     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
438     /// such that (*this == LHS + Separator + RHS) is true and RHS is
439     /// maximal. If \p Separator is not in the string, then the result is a
440     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
441     ///
442     /// \param Separator The character to split on.
443     /// \returns The split substrings.
444     std::pair<StringRef, StringRef> split(char Separator) const {
445       size_t Idx = find(Separator);
446       if (Idx == npos)
447         return std::make_pair(*this, StringRef());
448       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
449     }
450
451     /// Split into two substrings around the first occurrence of a separator
452     /// string.
453     ///
454     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
455     /// such that (*this == LHS + Separator + RHS) is true and RHS is
456     /// maximal. If \p Separator is not in the string, then the result is a
457     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
458     ///
459     /// \param Separator - The string to split on.
460     /// \return - The split substrings.
461     std::pair<StringRef, StringRef> split(StringRef Separator) const {
462       size_t Idx = find(Separator);
463       if (Idx == npos)
464         return std::make_pair(*this, StringRef());
465       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
466     }
467
468     /// Split into substrings around the occurrences of a separator string.
469     ///
470     /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
471     /// \p MaxSplit splits are done and consequently <= \p MaxSplit
472     /// elements are added to A.
473     /// If \p KeepEmpty is false, empty strings are not added to \p A. They
474     /// still count when considering \p MaxSplit
475     /// An useful invariant is that
476     /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
477     ///
478     /// \param A - Where to put the substrings.
479     /// \param Separator - The string to split on.
480     /// \param MaxSplit - The maximum number of times the string is split.
481     /// \param KeepEmpty - True if empty substring should be added.
482     void split(SmallVectorImpl<StringRef> &A,
483                StringRef Separator, int MaxSplit = -1,
484                bool KeepEmpty = true) const;
485
486     /// Split into two substrings around the last occurrence of a separator
487     /// character.
488     ///
489     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
490     /// such that (*this == LHS + Separator + RHS) is true and RHS is
491     /// minimal. If \p Separator is not in the string, then the result is a
492     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
493     ///
494     /// \param Separator - The character to split on.
495     /// \return - The split substrings.
496     std::pair<StringRef, StringRef> rsplit(char Separator) const {
497       size_t Idx = rfind(Separator);
498       if (Idx == npos)
499         return std::make_pair(*this, StringRef());
500       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
501     }
502
503     /// Return string with consecutive characters in \p Chars starting from
504     /// the left removed.
505     StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
506       return drop_front(std::min(Length, find_first_not_of(Chars)));
507     }
508
509     /// Return string with consecutive characters in \p Chars starting from
510     /// the right removed.
511     StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
512       return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
513     }
514
515     /// Return string with consecutive characters in \p Chars starting from
516     /// the left and right removed.
517     StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
518       return ltrim(Chars).rtrim(Chars);
519     }
520
521     /// @}
522   };
523
524   /// @name StringRef Comparison Operators
525   /// @{
526
527   inline bool operator==(StringRef LHS, StringRef RHS) {
528     return LHS.equals(RHS);
529   }
530
531   inline bool operator!=(StringRef LHS, StringRef RHS) {
532     return !(LHS == RHS);
533   }
534
535   inline bool operator<(StringRef LHS, StringRef RHS) {
536     return LHS.compare(RHS) == -1;
537   }
538
539   inline bool operator<=(StringRef LHS, StringRef RHS) {
540     return LHS.compare(RHS) != 1;
541   }
542
543   inline bool operator>(StringRef LHS, StringRef RHS) {
544     return LHS.compare(RHS) == 1;
545   }
546
547   inline bool operator>=(StringRef LHS, StringRef RHS) {
548     return LHS.compare(RHS) != -1;
549   }
550
551   inline std::string &operator+=(std::string &buffer, StringRef string) {
552     return buffer.append(string.data(), string.size());
553   }
554
555   /// @}
556
557   /// \brief Compute a hash_code for a StringRef.
558   hash_code hash_value(StringRef S);
559
560   // StringRefs can be treated like a POD type.
561   template <typename T> struct isPodLike;
562   template <> struct isPodLike<StringRef> { static const bool value = true; };
563 }
564
565 #endif