Fix typo in comment.
[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
15 #include <algorithm>
16 #include <cassert>
17 #include <cstring>
18 #include <limits>
19 #include <string>
20 #include <utility>
21
22 namespace llvm {
23   template<typename T>
24   class SmallVectorImpl;
25   class APInt;
26   class hash_code;
27   class StringRef;
28
29   /// Helper functions for StringRef::getAsInteger.
30   bool getAsUnsignedInteger(StringRef Str, unsigned Radix,
31                             unsigned long long &Result);
32
33   bool getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result);
34
35   /// StringRef - Represent a constant reference to a string, i.e. a character
36   /// array and a length, which need not be null terminated.
37   ///
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.
42   class StringRef {
43   public:
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;
48
49   private:
50     /// The start of the string, in an external buffer.
51     const char *Data;
52
53     /// The length of the string.
54     size_t Length;
55
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; }
61     
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);
67     }
68     
69   public:
70     /// @name Constructors
71     /// @{
72
73     /// Construct an empty string ref.
74     /*implicit*/ StringRef() : Data(0), Length(0) {}
75
76     /// Construct a string ref from a cstring.
77     /*implicit*/ StringRef(const char *Str)
78       : Data(Str) {
79         assert(Str && "StringRef cannot be built from a NULL argument");
80         Length = ::strlen(Str); // invoking strlen(NULL) is undefined behavior
81       }
82
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");
88       }
89
90     /// Construct a string ref from an std::string.
91     /*implicit*/ StringRef(const std::string &Str)
92       : Data(Str.data()), Length(Str.length()) {}
93
94     /// @}
95     /// @name Iterators
96     /// @{
97
98     iterator begin() const { return Data; }
99
100     iterator end() const { return Data + Length; }
101
102     /// @}
103     /// @name String Operations
104     /// @{
105
106     /// data - Get a pointer to the start of the string (which may not be null
107     /// terminated).
108     const char *data() const { return Data; }
109
110     /// empty - Check if the string is empty.
111     bool empty() const { return Length == 0; }
112
113     /// size - Get the string size.
114     size_t size() const { return Length; }
115
116     /// front - Get the first character in the string.
117     char front() const {
118       assert(!empty());
119       return Data[0];
120     }
121
122     /// back - Get the last character in the string.
123     char back() const {
124       assert(!empty());
125       return Data[Length-1];
126     }
127
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);
133     }
134
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;
138     }
139
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 \arg 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;
146
147       // Otherwise the prefixes match, so we only need to check the lengths.
148       if (Length == RHS.Length)
149         return 0;
150       return Length < RHS.Length ? -1 : 1;
151     }
152
153     /// compare_lower - Compare two strings, ignoring case.
154     int compare_lower(StringRef RHS) const;
155
156     /// compare_numeric - Compare two strings, treating sequences of digits as
157     /// numbers.
158     int compare_numeric(StringRef RHS) const;
159
160     /// \brief Determine the edit distance between this string and another
161     /// string.
162     ///
163     /// \param Other the string to compare this string against.
164     ///
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
168     /// removal).
169     ///
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.
173     ///
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);
180
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);
185     }
186
187     /// @}
188     /// @name Operator Overloads
189     /// @{
190
191     char operator[](size_t Index) const {
192       assert(Index < Length && "Invalid index!");
193       return Data[Index];
194     }
195
196     /// @}
197     /// @name Type Conversions
198     /// @{
199
200     operator std::string() const {
201       return str();
202     }
203
204     /// @}
205     /// @name String Predicates
206     /// @{
207
208     /// startswith - Check if this string starts with the given \arg Prefix.
209     bool startswith(StringRef Prefix) const {
210       return Length >= Prefix.Length &&
211              compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
212     }
213
214     /// endswith - Check if this string ends with the given \arg Suffix.
215     bool endswith(StringRef Suffix) const {
216       return Length >= Suffix.Length &&
217         compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
218     }
219
220     /// @}
221     /// @name String Searching
222     /// @{
223
224     /// find - Search for the first character \arg C in the string.
225     ///
226     /// \return - The index of the first occurrence of \arg C, or npos if not
227     /// found.
228     size_t find(char C, size_t From = 0) const {
229       for (size_t i = min(From, Length), e = Length; i != e; ++i)
230         if (Data[i] == C)
231           return i;
232       return npos;
233     }
234
235     /// find - Search for the first string \arg Str in the string.
236     ///
237     /// \return - The index of the first occurrence of \arg Str, or npos if not
238     /// found.
239     size_t find(StringRef Str, size_t From = 0) const;
240
241     /// rfind - Search for the last character \arg C in the string.
242     ///
243     /// \return - The index of the last occurrence of \arg C, or npos if not
244     /// found.
245     size_t rfind(char C, size_t From = npos) const {
246       From = min(From, Length);
247       size_t i = From;
248       while (i != 0) {
249         --i;
250         if (Data[i] == C)
251           return i;
252       }
253       return npos;
254     }
255
256     /// rfind - Search for the last string \arg Str in the string.
257     ///
258     /// \return - The index of the last occurrence of \arg Str, or npos if not
259     /// found.
260     size_t rfind(StringRef Str) const;
261
262     /// find_first_of - Find the first character in the string that is \arg C,
263     /// or npos if not found. Same as find.
264     size_type find_first_of(char C, size_t From = 0) const {
265       return find(C, From);
266     }
267
268     /// find_first_of - Find the first character in the string that is in \arg
269     /// Chars, or npos if not found.
270     ///
271     /// Note: O(size() + Chars.size())
272     size_type find_first_of(StringRef Chars, size_t From = 0) const;
273
274     /// find_first_not_of - Find the first character in the string that is not
275     /// \arg C or npos if not found.
276     size_type find_first_not_of(char C, size_t From = 0) const;
277
278     /// find_first_not_of - Find the first character in the string that is not
279     /// in the string \arg Chars, or npos if not found.
280     ///
281     /// Note: O(size() + Chars.size())
282     size_type find_first_not_of(StringRef Chars, size_t From = 0) const;
283
284     /// find_last_of - Find the last character in the string that is \arg C, or
285     /// npos if not found.
286     size_type find_last_of(char C, size_t From = npos) const {
287       return rfind(C, From);
288     }
289
290     /// find_last_of - Find the last character in the string that is in \arg C,
291     /// or npos if not found.
292     ///
293     /// Note: O(size() + Chars.size())
294     size_type find_last_of(StringRef Chars, size_t From = npos) const;
295
296     /// find_last_not_of - Find the last character in the string that is not
297     /// \arg C, or npos if not found.
298     size_type find_last_not_of(char C, size_t From = npos) const;
299
300     /// find_last_not_of - Find the last character in the string that is not in
301     /// \arg Chars, or npos if not found.
302     ///
303     /// Note: O(size() + Chars.size())
304     size_type find_last_not_of(StringRef Chars, size_t From = npos) const;
305
306     /// @}
307     /// @name Helpful Algorithms
308     /// @{
309
310     /// count - Return the number of occurrences of \arg C in the string.
311     size_t count(char C) const {
312       size_t Count = 0;
313       for (size_t i = 0, e = Length; i != e; ++i)
314         if (Data[i] == C)
315           ++Count;
316       return Count;
317     }
318
319     /// count - Return the number of non-overlapped occurrences of \arg Str in
320     /// the string.
321     size_t count(StringRef Str) const;
322
323     /// getAsInteger - Parse the current string as an integer of the specified
324     /// radix.  If Radix is specified as zero, this does radix autosensing using
325     /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
326     ///
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     ///
331     template <typename T>
332     typename enable_if_c<std::numeric_limits<T>::is_signed, bool>::type
333     getAsInteger(unsigned Radix, T &Result) const {
334       long long LLVal;
335       if (getAsSignedInteger(*this, Radix, LLVal) ||
336             static_cast<T>(LLVal) != LLVal)
337         return true;
338       Result = LLVal;
339       return false;
340     }
341
342     template <typename T>
343     typename enable_if_c<!std::numeric_limits<T>::is_signed, bool>::type
344     getAsInteger(unsigned Radix, T &Result) const {
345       unsigned long long ULLVal;
346       if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
347             static_cast<T>(ULLVal) != ULLVal)
348         return true;
349       Result = ULLVal;
350       return false;
351     }
352
353     /// getAsInteger - Parse the current string as an integer of the
354     /// specified radix, or of an autosensed radix if the radix given
355     /// is 0.  The current value in Result is discarded, and the
356     /// storage is changed to be wide enough to store the parsed
357     /// integer.
358     ///
359     /// Returns true if the string does not solely consist of a valid
360     /// non-empty number in the appropriate base.
361     ///
362     /// APInt::fromString is superficially similar but assumes the
363     /// string is well-formed in the given radix.
364     bool getAsInteger(unsigned Radix, APInt &Result) const;
365
366     /// @}
367     /// @name String Operations
368     /// @{
369
370     // lower - Convert the given ASCII string to lowercase.
371     std::string lower() const;
372
373     /// upper - Convert the given ASCII string to uppercase.
374     std::string upper() const;
375
376     /// @}
377     /// @name Substring Operations
378     /// @{
379
380     /// substr - Return a reference to the substring from [Start, Start + N).
381     ///
382     /// \param Start - The index of the starting character in the substring; if
383     /// the index is npos or greater than the length of the string then the
384     /// empty substring will be returned.
385     ///
386     /// \param N - The number of characters to included in the substring. If N
387     /// exceeds the number of characters remaining in the string, the string
388     /// suffix (starting with \arg Start) will be returned.
389     StringRef substr(size_t Start, size_t N = npos) const {
390       Start = min(Start, Length);
391       return StringRef(Data + Start, min(N, Length - Start));
392     }
393     
394     /// drop_front - Return a StringRef equal to 'this' but with the first
395     /// elements dropped.
396     StringRef drop_front(unsigned N = 1) const {
397       assert(size() >= N && "Dropping more elements than exist");
398       return substr(N);
399     }
400
401     /// drop_back - Return a StringRef equal to 'this' but with the last
402     /// elements dropped.
403     StringRef drop_back(unsigned N = 1) const {
404       assert(size() >= N && "Dropping more elements than exist");
405       return substr(0, size()-N);
406     }
407
408     /// slice - Return a reference to the substring from [Start, End).
409     ///
410     /// \param Start - The index of the starting character in the substring; if
411     /// the index is npos or greater than the length of the string then the
412     /// empty substring will be returned.
413     ///
414     /// \param End - The index following the last character to include in the
415     /// substring. If this is npos, or less than \arg Start, or exceeds the
416     /// number of characters remaining in the string, the string suffix
417     /// (starting with \arg Start) will be returned.
418     StringRef slice(size_t Start, size_t End) const {
419       Start = min(Start, Length);
420       End = min(max(Start, End), Length);
421       return StringRef(Data + Start, End - Start);
422     }
423
424     /// split - Split into two substrings around the first occurrence of a
425     /// separator character.
426     ///
427     /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
428     /// such that (*this == LHS + Separator + RHS) is true and RHS is
429     /// maximal. If \arg Separator is not in the string, then the result is a
430     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
431     ///
432     /// \param Separator - The character to split on.
433     /// \return - The split substrings.
434     std::pair<StringRef, StringRef> split(char Separator) const {
435       size_t Idx = find(Separator);
436       if (Idx == npos)
437         return std::make_pair(*this, StringRef());
438       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
439     }
440
441     /// split - Split into two substrings around the first occurrence of a
442     /// separator string.
443     ///
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     /// maximal. If \arg Separator is not in the string, then the result is a
447     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
448     ///
449     /// \param Separator - The string to split on.
450     /// \return - The split substrings.
451     std::pair<StringRef, StringRef> split(StringRef Separator) const {
452       size_t Idx = find(Separator);
453       if (Idx == npos)
454         return std::make_pair(*this, StringRef());
455       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
456     }
457
458     /// split - Split into substrings around the occurrences of a separator
459     /// string.
460     ///
461     /// Each substring is stored in \arg A. If \arg MaxSplit is >= 0, at most
462     /// \arg MaxSplit splits are done and consequently <= \arg MaxSplit
463     /// elements are added to A.
464     /// If \arg KeepEmpty is false, empty strings are not added to \arg A. They
465     /// still count when considering \arg 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     /// rsplit - Split into two substrings around the last occurrence of a
478     /// separator character.
479     ///
480     /// If \arg 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 \arg 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     /// ltrim - Return string with consecutive characters in \arg Chars starting
495     /// from 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     /// rtrim - Return string with consecutive characters in \arg Chars starting
501     /// from 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     /// trim - Return string with consecutive characters in \arg Chars starting
507     /// from 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, llvm::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