56848fb61672dc16027827b30983231881ea2d79
[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/type_traits.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(0), 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     /// Construct a string ref from a boolean.
94     explicit StringRef(bool B)
95       : Data(B ? "true" : "false"), Length(::strlen(Data)) {}
96
97     /// @}
98     /// @name Iterators
99     /// @{
100
101     iterator begin() const { return Data; }
102
103     iterator end() const { return Data + Length; }
104
105     /// @}
106     /// @name String Operations
107     /// @{
108
109     /// data - Get a pointer to the start of the string (which may not be null
110     /// terminated).
111     const char *data() const { return Data; }
112
113     /// empty - Check if the string is empty.
114     bool empty() const { return Length == 0; }
115
116     /// size - Get the string size.
117     size_t size() const { return Length; }
118
119     /// front - Get the first character in the string.
120     char front() const {
121       assert(!empty());
122       return Data[0];
123     }
124
125     /// back - Get the last character in the string.
126     char back() const {
127       assert(!empty());
128       return Data[Length-1];
129     }
130
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);
136     }
137
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;
141     }
142
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;
149
150       // Otherwise the prefixes match, so we only need to check the lengths.
151       if (Length == RHS.Length)
152         return 0;
153       return Length < RHS.Length ? -1 : 1;
154     }
155
156     /// compare_lower - Compare two strings, ignoring case.
157     int compare_lower(StringRef RHS) const;
158
159     /// compare_numeric - Compare two strings, treating sequences of digits as
160     /// numbers.
161     int compare_numeric(StringRef RHS) const;
162
163     /// \brief Determine the edit distance between this string and another
164     /// string.
165     ///
166     /// \param Other the string to compare this string against.
167     ///
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
171     /// removal).
172     ///
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.
176     ///
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);
183
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);
188     }
189
190     /// @}
191     /// @name Operator Overloads
192     /// @{
193
194     char operator[](size_t Index) const {
195       assert(Index < Length && "Invalid index!");
196       return Data[Index];
197     }
198
199     /// @}
200     /// @name Type Conversions
201     /// @{
202
203     operator std::string() const {
204       return str();
205     }
206
207     /// @}
208     /// @name String Predicates
209     /// @{
210
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;
215     }
216
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;
221     }
222
223     /// @}
224     /// @name String Searching
225     /// @{
226
227     /// Search for the first character \p C in the string.
228     ///
229     /// \returns The index of the first occurrence of \p C, or npos if not
230     /// found.
231     size_t find(char C, size_t From = 0) const {
232       for (size_t i = min(From, Length), e = Length; i != e; ++i)
233         if (Data[i] == C)
234           return i;
235       return npos;
236     }
237
238     /// Search for the first string \p Str in the string.
239     ///
240     /// \returns The index of the first occurrence of \p Str, or npos if not
241     /// found.
242     size_t find(StringRef Str, size_t From = 0) const;
243
244     /// Search for the last character \p C in the string.
245     ///
246     /// \returns The index of the last occurrence of \p C, or npos if not
247     /// found.
248     size_t rfind(char C, size_t From = npos) const {
249       From = min(From, Length);
250       size_t i = From;
251       while (i != 0) {
252         --i;
253         if (Data[i] == C)
254           return i;
255       }
256       return npos;
257     }
258
259     /// Search for the last string \p Str in the string.
260     ///
261     /// \returns The index of the last occurrence of \p Str, or npos if not
262     /// found.
263     size_t rfind(StringRef Str) const;
264
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);
269     }
270
271     /// Find the first character in the string that is in \p Chars, or npos if
272     /// not found.
273     ///
274     /// Complexity: O(size() + Chars.size())
275     size_t find_first_of(StringRef Chars, size_t From = 0) const;
276
277     /// Find the first character in the string that is not \p C or npos if not
278     /// found.
279     size_t find_first_not_of(char C, size_t From = 0) const;
280
281     /// Find the first character in the string that is not in the string
282     /// \p Chars, or npos if not found.
283     ///
284     /// Complexity: O(size() + Chars.size())
285     size_t find_first_not_of(StringRef Chars, size_t From = 0) const;
286
287     /// Find the last character in the string that is \p C, or npos if not
288     /// found.
289     size_t find_last_of(char C, size_t From = npos) const {
290       return rfind(C, From);
291     }
292
293     /// Find the last character in the string that is in \p C, or npos if not
294     /// found.
295     ///
296     /// Complexity: O(size() + Chars.size())
297     size_t find_last_of(StringRef Chars, size_t From = npos) const;
298
299     /// Find the last character in the string that is not \p C, or npos if not
300     /// found.
301     size_t find_last_not_of(char C, size_t From = npos) const;
302
303     /// Find the last character in the string that is not in \p Chars, or
304     /// npos if not found.
305     ///
306     /// Complexity: O(size() + Chars.size())
307     size_t find_last_not_of(StringRef Chars, size_t From = npos) const;
308
309     /// @}
310     /// @name Helpful Algorithms
311     /// @{
312
313     /// Return the number of occurrences of \p C in the string.
314     size_t count(char C) const {
315       size_t Count = 0;
316       for (size_t i = 0, e = Length; i != e; ++i)
317         if (Data[i] == C)
318           ++Count;
319       return Count;
320     }
321
322     /// Return the number of non-overlapped occurrences of \p Str in
323     /// the string.
324     size_t count(StringRef Str) const;
325
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.
329     ///
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 {
336       long long LLVal;
337       if (getAsSignedInteger(*this, Radix, LLVal) ||
338             static_cast<T>(LLVal) != LLVal)
339         return true;
340       Result = LLVal;
341       return false;
342     }
343
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)
350         return true;
351       Result = ULLVal;
352       return false;
353     }
354
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.
359     ///
360     /// \returns true if the string does not solely consist of a valid
361     /// non-empty number in the appropriate base.
362     ///
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;
366
367     /// @}
368     /// @name String Operations
369     /// @{
370
371     // Convert the given ASCII string to lowercase.
372     std::string lower() const;
373
374     /// Convert the given ASCII string to uppercase.
375     std::string upper() const;
376
377     /// @}
378     /// @name Substring Operations
379     /// @{
380
381     /// Return a reference to the substring from [Start, Start + N).
382     ///
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.
386     ///
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));
393     }
394
395     /// Return a StringRef equal to 'this' but with the first \p N elements
396     /// dropped.
397     StringRef drop_front(size_t N = 1) const {
398       assert(size() >= N && "Dropping more elements than exist");
399       return substr(N);
400     }
401
402     /// Return a StringRef equal to 'this' but with the last \p N elements
403     /// dropped.
404     StringRef drop_back(size_t N = 1) const {
405       assert(size() >= N && "Dropping more elements than exist");
406       return substr(0, size()-N);
407     }
408
409     /// Return a reference to the substring from [Start, End).
410     ///
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.
414     ///
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);
423     }
424
425     /// Split into two substrings around the first occurrence of a separator
426     /// character.
427     ///
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 == "").
432     ///
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);
437       if (Idx == npos)
438         return std::make_pair(*this, StringRef());
439       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
440     }
441
442     /// Split into two substrings around the first occurrence of a separator
443     /// string.
444     ///
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 == "").
449     ///
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);
454       if (Idx == npos)
455         return std::make_pair(*this, StringRef());
456       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
457     }
458
459     /// Split into substrings around the occurrences of a separator string.
460     ///
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
468     ///
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;
476
477     /// Split into two substrings around the last occurrence of a separator
478     /// character.
479     ///
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 == "").
484     ///
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);
489       if (Idx == npos)
490         return std::make_pair(*this, StringRef());
491       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
492     }
493
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)));
498     }
499
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));
504     }
505
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);
510     }
511
512     /// @}
513   };
514
515   /// @name StringRef Comparison Operators
516   /// @{
517
518   inline bool operator==(StringRef LHS, StringRef RHS) {
519     return LHS.equals(RHS);
520   }
521
522   inline bool operator!=(StringRef LHS, StringRef RHS) {
523     return !(LHS == RHS);
524   }
525
526   inline bool operator<(StringRef LHS, StringRef RHS) {
527     return LHS.compare(RHS) == -1;
528   }
529
530   inline bool operator<=(StringRef LHS, StringRef RHS) {
531     return LHS.compare(RHS) != 1;
532   }
533
534   inline bool operator>(StringRef LHS, StringRef RHS) {
535     return LHS.compare(RHS) == 1;
536   }
537
538   inline bool operator>=(StringRef LHS, StringRef RHS) {
539     return LHS.compare(RHS) != -1;
540   }
541
542   inline std::string &operator+=(std::string &buffer, StringRef string) {
543     return buffer.append(string.data(), string.size());
544   }
545
546   /// @}
547
548   /// \brief Compute a hash_code for a StringRef.
549   hash_code hash_value(StringRef S);
550
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; };
554
555 }
556
557 #endif