Add an override to StringRef::getAsInteger which parses into an APInt.
[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 <cassert>
14 #include <cstring>
15 #include <utility>
16 #include <string>
17
18 namespace llvm {
19   template<typename T>
20   class SmallVectorImpl;
21   class APInt;
22
23   /// StringRef - Represent a constant reference to a string, i.e. a character
24   /// array and a length, which need not be null terminated.
25   ///
26   /// This class does not own the string data, it is expected to be used in
27   /// situations where the character data resides in some other buffer, whose
28   /// lifetime extends past that of the StringRef. For this reason, it is not in
29   /// general safe to store a StringRef.
30   class StringRef {
31   public:
32     typedef const char *iterator;
33     typedef const char *const_iterator;
34     static const size_t npos = ~size_t(0);
35     typedef size_t size_type;
36
37   private:
38     /// The start of the string, in an external buffer.
39     const char *Data;
40
41     /// The length of the string.
42     size_t Length;
43
44     // Workaround PR5482: nearly all gcc 4.x miscompile StringRef and std::min()
45     // Changing the arg of min to be an integer, instead of a reference to an
46     // integer works around this bug.
47     size_t min(size_t a, size_t b) const { return a < b ? a : b; }
48     size_t max(size_t a, size_t b) const { return a > b ? a : b; }
49
50   public:
51     /// @name Constructors
52     /// @{
53
54     /// Construct an empty string ref.
55     /*implicit*/ StringRef() : Data(0), Length(0) {}
56
57     /// Construct a string ref from a cstring.
58     /*implicit*/ StringRef(const char *Str)
59       : Data(Str), Length(::strlen(Str)) {}
60
61     /// Construct a string ref from a pointer and length.
62     /*implicit*/ StringRef(const char *data, size_t length)
63       : Data(data), Length(length) {}
64
65     /// Construct a string ref from an std::string.
66     /*implicit*/ StringRef(const std::string &Str)
67       : Data(Str.data()), Length(Str.length()) {}
68
69     /// @}
70     /// @name Iterators
71     /// @{
72
73     iterator begin() const { return Data; }
74
75     iterator end() const { return Data + Length; }
76
77     /// @}
78     /// @name String Operations
79     /// @{
80
81     /// data - Get a pointer to the start of the string (which may not be null
82     /// terminated).
83     const char *data() const { return Data; }
84
85     /// empty - Check if the string is empty.
86     bool empty() const { return Length == 0; }
87
88     /// size - Get the string size.
89     size_t size() const { return Length; }
90
91     /// front - Get the first character in the string.
92     char front() const {
93       assert(!empty());
94       return Data[0];
95     }
96
97     /// back - Get the last character in the string.
98     char back() const {
99       assert(!empty());
100       return Data[Length-1];
101     }
102
103     /// equals - Check for string equality, this is more efficient than
104     /// compare() when the relative ordering of inequal strings isn't needed.
105     bool equals(StringRef RHS) const {
106       return (Length == RHS.Length &&
107               memcmp(Data, RHS.Data, RHS.Length) == 0);
108     }
109
110     /// equals_lower - Check for string equality, ignoring case.
111     bool equals_lower(StringRef RHS) const {
112       return Length == RHS.Length && compare_lower(RHS) == 0;
113     }
114
115     /// compare - Compare two strings; the result is -1, 0, or 1 if this string
116     /// is lexicographically less than, equal to, or greater than the \arg RHS.
117     int compare(StringRef RHS) const {
118       // Check the prefix for a mismatch.
119       if (int Res = memcmp(Data, RHS.Data, min(Length, RHS.Length)))
120         return Res < 0 ? -1 : 1;
121
122       // Otherwise the prefixes match, so we only need to check the lengths.
123       if (Length == RHS.Length)
124         return 0;
125       return Length < RHS.Length ? -1 : 1;
126     }
127
128     /// compare_lower - Compare two strings, ignoring case.
129     int compare_lower(StringRef RHS) const;
130
131     /// \brief Determine the edit distance between this string and another 
132     /// string.
133     ///
134     /// \param Other the string to compare this string against.
135     ///
136     /// \param AllowReplacements whether to allow character
137     /// replacements (change one character into another) as a single
138     /// operation, rather than as two operations (an insertion and a
139     /// removal).
140     ///
141     /// \returns the minimum number of character insertions, removals,
142     /// or (if \p AllowReplacements is \c true) replacements needed to
143     /// transform one of the given strings into the other. If zero,
144     /// the strings are identical.
145     unsigned edit_distance(StringRef Other, bool AllowReplacements = true);
146
147     /// str - Get the contents as an std::string.
148     std::string str() const { return std::string(Data, Length); }
149
150     /// @}
151     /// @name Operator Overloads
152     /// @{
153
154     char operator[](size_t Index) const {
155       assert(Index < Length && "Invalid index!");
156       return Data[Index];
157     }
158
159     /// @}
160     /// @name Type Conversions
161     /// @{
162
163     operator std::string() const {
164       return str();
165     }
166
167     /// @}
168     /// @name String Predicates
169     /// @{
170
171     /// startswith - Check if this string starts with the given \arg Prefix.
172     bool startswith(StringRef Prefix) const {
173       return Length >= Prefix.Length &&
174              memcmp(Data, Prefix.Data, Prefix.Length) == 0;
175     }
176
177     /// endswith - Check if this string ends with the given \arg Suffix.
178     bool endswith(StringRef Suffix) const {
179       return Length >= Suffix.Length &&
180              memcmp(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
181     }
182
183     /// @}
184     /// @name String Searching
185     /// @{
186
187     /// find - Search for the first character \arg C in the string.
188     ///
189     /// \return - The index of the first occurrence of \arg C, or npos if not
190     /// found.
191     size_t find(char C, size_t From = 0) const {
192       for (size_t i = min(From, Length), e = Length; i != e; ++i)
193         if (Data[i] == C)
194           return i;
195       return npos;
196     }
197
198     /// find - Search for the first string \arg Str in the string.
199     ///
200     /// \return - The index of the first occurrence of \arg Str, or npos if not
201     /// found.
202     size_t find(StringRef Str, size_t From = 0) const;
203
204     /// rfind - Search for the last character \arg C in the string.
205     ///
206     /// \return - The index of the last occurrence of \arg C, or npos if not
207     /// found.
208     size_t rfind(char C, size_t From = npos) const {
209       From = min(From, Length);
210       size_t i = From;
211       while (i != 0) {
212         --i;
213         if (Data[i] == C)
214           return i;
215       }
216       return npos;
217     }
218
219     /// rfind - Search for the last string \arg Str in the string.
220     ///
221     /// \return - The index of the last occurrence of \arg Str, or npos if not
222     /// found.
223     size_t rfind(StringRef Str) const;
224
225     /// find_first_of - Find the first character in the string that is \arg C,
226     /// or npos if not found. Same as find.
227     size_type find_first_of(char C, size_t = 0) const { return find(C); }
228
229     /// find_first_of - Find the first character in the string that is in \arg
230     /// Chars, or npos if not found.
231     ///
232     /// Note: O(size() * Chars.size())
233     size_type find_first_of(StringRef Chars, size_t From = 0) const;
234
235     /// find_first_not_of - Find the first character in the string that is not
236     /// \arg C or npos if not found.
237     size_type find_first_not_of(char C, size_t From = 0) const;
238
239     /// find_first_not_of - Find the first character in the string that is not
240     /// in the string \arg Chars, or npos if not found.
241     ///
242     /// Note: O(size() * Chars.size())
243     size_type find_first_not_of(StringRef Chars, size_t From = 0) const;
244
245     /// @}
246     /// @name Helpful Algorithms
247     /// @{
248
249     /// count - Return the number of occurrences of \arg C in the string.
250     size_t count(char C) const {
251       size_t Count = 0;
252       for (size_t i = 0, e = Length; i != e; ++i)
253         if (Data[i] == C)
254           ++Count;
255       return Count;
256     }
257
258     /// count - Return the number of non-overlapped occurrences of \arg Str in
259     /// the string.
260     size_t count(StringRef Str) const;
261
262     /// getAsInteger - Parse the current string as an integer of the specified
263     /// radix.  If Radix is specified as zero, this does radix autosensing using
264     /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
265     ///
266     /// If the string is invalid or if only a subset of the string is valid,
267     /// this returns true to signify the error.  The string is considered
268     /// erroneous if empty.
269     ///
270     bool getAsInteger(unsigned Radix, long long &Result) const;
271     bool getAsInteger(unsigned Radix, unsigned long long &Result) const;
272     bool getAsInteger(unsigned Radix, int &Result) const;
273     bool getAsInteger(unsigned Radix, unsigned &Result) const;
274
275     // TODO: Provide overloads for int/unsigned that check for overflow.
276
277     /// getAsInteger - Parse the current string as an integer of the
278     /// specified radix, or of an autosensed radix if the radix given
279     /// is 0.  The current value in Result is discarded, and the
280     /// storage is changed to be wide enough to store the parsed
281     /// integer.
282     ///
283     /// Returns true if the string does not solely consist of a valid
284     /// non-empty number in the appropriate base.
285     ///
286     /// APInt::fromString is superficially similar but assumes the
287     /// string is well-formed in the given radix.
288     bool getAsInteger(unsigned Radix, APInt &Result) const;
289
290     /// @}
291     /// @name Substring Operations
292     /// @{
293
294     /// substr - Return a reference to the substring from [Start, Start + N).
295     ///
296     /// \param Start - The index of the starting character in the substring; if
297     /// the index is npos or greater than the length of the string then the
298     /// empty substring will be returned.
299     ///
300     /// \param N - The number of characters to included in the substring. If N
301     /// exceeds the number of characters remaining in the string, the string
302     /// suffix (starting with \arg Start) will be returned.
303     StringRef substr(size_t Start, size_t N = npos) const {
304       Start = min(Start, Length);
305       return StringRef(Data + Start, min(N, Length - Start));
306     }
307
308     /// slice - Return a reference to the substring from [Start, End).
309     ///
310     /// \param Start - The index of the starting character in the substring; if
311     /// the index is npos or greater than the length of the string then the
312     /// empty substring will be returned.
313     ///
314     /// \param End - The index following the last character to include in the
315     /// substring. If this is npos, or less than \arg Start, or exceeds the
316     /// number of characters remaining in the string, the string suffix
317     /// (starting with \arg Start) will be returned.
318     StringRef slice(size_t Start, size_t End) const {
319       Start = min(Start, Length);
320       End = min(max(Start, End), Length);
321       return StringRef(Data + Start, End - Start);
322     }
323
324     /// split - Split into two substrings around the first occurrence of a
325     /// separator character.
326     ///
327     /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
328     /// such that (*this == LHS + Separator + RHS) is true and RHS is
329     /// maximal. If \arg Separator is not in the string, then the result is a
330     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
331     ///
332     /// \param Separator - The character to split on.
333     /// \return - The split substrings.
334     std::pair<StringRef, StringRef> split(char Separator) const {
335       size_t Idx = find(Separator);
336       if (Idx == npos)
337         return std::make_pair(*this, StringRef());
338       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
339     }
340
341     /// split - Split into two substrings around the first occurrence of a
342     /// separator string.
343     ///
344     /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
345     /// such that (*this == LHS + Separator + RHS) is true and RHS is
346     /// maximal. If \arg Separator is not in the string, then the result is a
347     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
348     ///
349     /// \param Separator - The string to split on.
350     /// \return - The split substrings.
351     std::pair<StringRef, StringRef> split(StringRef Separator) const {
352       size_t Idx = find(Separator);
353       if (Idx == npos)
354         return std::make_pair(*this, StringRef());
355       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
356     }
357
358     /// split - Split into substrings around the occurrences of a separator
359     /// string.
360     ///
361     /// Each substring is stored in \arg A. If \arg MaxSplit is >= 0, at most
362     /// \arg MaxSplit splits are done and consequently <= \arg MaxSplit
363     /// elements are added to A.
364     /// If \arg KeepEmpty is false, empty strings are not added to \arg A. They
365     /// still count when considering \arg MaxSplit
366     /// An useful invariant is that
367     /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
368     ///
369     /// \param A - Where to put the substrings.
370     /// \param Separator - The string to split on.
371     /// \param MaxSplit - The maximum number of times the string is split.
372     /// \param KeepEmpty - True if empty substring should be added.
373     void split(SmallVectorImpl<StringRef> &A,
374                StringRef Separator, int MaxSplit = -1,
375                bool KeepEmpty = true) const;
376
377     /// rsplit - Split into two substrings around the last occurrence of a
378     /// separator character.
379     ///
380     /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
381     /// such that (*this == LHS + Separator + RHS) is true and RHS is
382     /// minimal. If \arg Separator is not in the string, then the result is a
383     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
384     ///
385     /// \param Separator - The character to split on.
386     /// \return - The split substrings.
387     std::pair<StringRef, StringRef> rsplit(char Separator) const {
388       size_t Idx = rfind(Separator);
389       if (Idx == npos)
390         return std::make_pair(*this, StringRef());
391       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
392     }
393
394     /// @}
395   };
396
397   /// @name StringRef Comparison Operators
398   /// @{
399
400   inline bool operator==(StringRef LHS, StringRef RHS) {
401     return LHS.equals(RHS);
402   }
403
404   inline bool operator!=(StringRef LHS, StringRef RHS) {
405     return !(LHS == RHS);
406   }
407
408   inline bool operator<(StringRef LHS, StringRef RHS) {
409     return LHS.compare(RHS) == -1;
410   }
411
412   inline bool operator<=(StringRef LHS, StringRef RHS) {
413     return LHS.compare(RHS) != 1;
414   }
415
416   inline bool operator>(StringRef LHS, StringRef RHS) {
417     return LHS.compare(RHS) == 1;
418   }
419
420   inline bool operator>=(StringRef LHS, StringRef RHS) {
421     return LHS.compare(RHS) != -1;
422   }
423
424   /// @}
425
426 }
427
428 #endif