Implements StringRef::compare with bounds. It is behaves similarly to strncmp()....
[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     static size_t min(size_t a, size_t b) { return a < b ? a : b; }
48     static size_t max(size_t a, size_t b) { 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 - Compare two strings; the result is -1, 0, or 1 if this string
129     /// is lexicographically less than, equal to, or greater than the \arg RHS.
130     /// This is different than compare with no size specified as it only 
131     /// compares at most the first n bytes.
132     int compare(StringRef RHS, size_t n) const;
133
134     /// compare_lower - Compare two strings, ignoring case.
135     int compare_lower(StringRef RHS) const;
136
137     /// compare_numeric - Compare two strings, treating sequences of digits as
138     /// numbers.
139     int compare_numeric(StringRef RHS) const;
140
141     /// \brief Determine the edit distance between this string and another
142     /// string.
143     ///
144     /// \param Other the string to compare this string against.
145     ///
146     /// \param AllowReplacements whether to allow character
147     /// replacements (change one character into another) as a single
148     /// operation, rather than as two operations (an insertion and a
149     /// removal).
150     ///
151     /// \param MaxEditDistance If non-zero, the maximum edit distance that
152     /// this routine is allowed to compute. If the edit distance will exceed
153     /// that maximum, returns \c MaxEditDistance+1.
154     ///
155     /// \returns the minimum number of character insertions, removals,
156     /// or (if \p AllowReplacements is \c true) replacements needed to
157     /// transform one of the given strings into the other. If zero,
158     /// the strings are identical.
159     unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
160                            unsigned MaxEditDistance = 0);
161
162     /// str - Get the contents as an std::string.
163     std::string str() const {
164       if (Data == 0) return std::string();
165       return std::string(Data, Length);
166     }
167
168     /// @}
169     /// @name Operator Overloads
170     /// @{
171
172     char operator[](size_t Index) const {
173       assert(Index < Length && "Invalid index!");
174       return Data[Index];
175     }
176
177     /// @}
178     /// @name Type Conversions
179     /// @{
180
181     operator std::string() const {
182       return str();
183     }
184
185     /// @}
186     /// @name String Predicates
187     /// @{
188
189     /// startswith - Check if this string starts with the given \arg Prefix.
190     bool startswith(StringRef Prefix) const {
191       return Length >= Prefix.Length &&
192              memcmp(Data, Prefix.Data, Prefix.Length) == 0;
193     }
194
195     /// endswith - Check if this string ends with the given \arg Suffix.
196     bool endswith(StringRef Suffix) const {
197       return Length >= Suffix.Length &&
198              memcmp(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
199     }
200
201     /// @}
202     /// @name String Searching
203     /// @{
204
205     /// find - Search for the first character \arg C in the string.
206     ///
207     /// \return - The index of the first occurrence of \arg C, or npos if not
208     /// found.
209     size_t find(char C, size_t From = 0) const {
210       for (size_t i = min(From, Length), e = Length; i != e; ++i)
211         if (Data[i] == C)
212           return i;
213       return npos;
214     }
215
216     /// find - Search for the first string \arg Str in the string.
217     ///
218     /// \return - The index of the first occurrence of \arg Str, or npos if not
219     /// found.
220     size_t find(StringRef Str, size_t From = 0) const;
221
222     /// rfind - Search for the last character \arg C in the string.
223     ///
224     /// \return - The index of the last occurrence of \arg C, or npos if not
225     /// found.
226     size_t rfind(char C, size_t From = npos) const {
227       From = min(From, Length);
228       size_t i = From;
229       while (i != 0) {
230         --i;
231         if (Data[i] == C)
232           return i;
233       }
234       return npos;
235     }
236
237     /// rfind - Search for the last string \arg Str in the string.
238     ///
239     /// \return - The index of the last occurrence of \arg Str, or npos if not
240     /// found.
241     size_t rfind(StringRef Str) const;
242
243     /// find_first_of - Find the first character in the string that is \arg C,
244     /// or npos if not found. Same as find.
245     size_type find_first_of(char C, size_t From = 0) const {
246       return find(C, From);
247     }
248
249     /// find_first_of - Find the first character in the string that is in \arg
250     /// Chars, or npos if not found.
251     ///
252     /// Note: O(size() + Chars.size())
253     size_type find_first_of(StringRef Chars, size_t From = 0) const;
254
255     /// find_first_not_of - Find the first character in the string that is not
256     /// \arg C or npos if not found.
257     size_type find_first_not_of(char C, size_t From = 0) const;
258
259     /// find_first_not_of - Find the first character in the string that is not
260     /// in the string \arg Chars, or npos if not found.
261     ///
262     /// Note: O(size() + Chars.size())
263     size_type find_first_not_of(StringRef Chars, size_t From = 0) const;
264
265     /// find_last_of - Find the last character in the string that is \arg C, or
266     /// npos if not found.
267     size_type find_last_of(char C, size_t From = npos) const {
268       return rfind(C, From);
269     }
270
271     /// find_last_of - Find the last character in the string that is in \arg C,
272     /// or npos if not found.
273     ///
274     /// Note: O(size() + Chars.size())
275     size_type find_last_of(StringRef Chars, size_t From = npos) const;
276
277     /// @}
278     /// @name Helpful Algorithms
279     /// @{
280
281     /// count - Return the number of occurrences of \arg C in the string.
282     size_t count(char C) const {
283       size_t Count = 0;
284       for (size_t i = 0, e = Length; i != e; ++i)
285         if (Data[i] == C)
286           ++Count;
287       return Count;
288     }
289
290     /// count - Return the number of non-overlapped occurrences of \arg Str in
291     /// the string.
292     size_t count(StringRef Str) const;
293
294     /// getAsInteger - Parse the current string as an integer of the specified
295     /// radix.  If Radix is specified as zero, this does radix autosensing using
296     /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
297     ///
298     /// If the string is invalid or if only a subset of the string is valid,
299     /// this returns true to signify the error.  The string is considered
300     /// erroneous if empty.
301     ///
302     bool getAsInteger(unsigned Radix, long long &Result) const;
303     bool getAsInteger(unsigned Radix, unsigned long long &Result) const;
304     bool getAsInteger(unsigned Radix, int &Result) const;
305     bool getAsInteger(unsigned Radix, unsigned &Result) const;
306
307     // TODO: Provide overloads for int/unsigned that check for overflow.
308
309     /// getAsInteger - Parse the current string as an integer of the
310     /// specified radix, or of an autosensed radix if the radix given
311     /// is 0.  The current value in Result is discarded, and the
312     /// storage is changed to be wide enough to store the parsed
313     /// integer.
314     ///
315     /// Returns true if the string does not solely consist of a valid
316     /// non-empty number in the appropriate base.
317     ///
318     /// APInt::fromString is superficially similar but assumes the
319     /// string is well-formed in the given radix.
320     bool getAsInteger(unsigned Radix, APInt &Result) const;
321
322     /// @}
323     /// @name Substring Operations
324     /// @{
325
326     /// substr - Return a reference to the substring from [Start, Start + N).
327     ///
328     /// \param Start - The index of the starting character in the substring; if
329     /// the index is npos or greater than the length of the string then the
330     /// empty substring will be returned.
331     ///
332     /// \param N - The number of characters to included in the substring. If N
333     /// exceeds the number of characters remaining in the string, the string
334     /// suffix (starting with \arg Start) will be returned.
335     StringRef substr(size_t Start, size_t N = npos) const {
336       Start = min(Start, Length);
337       return StringRef(Data + Start, min(N, Length - Start));
338     }
339
340     /// slice - Return a reference to the substring from [Start, End).
341     ///
342     /// \param Start - The index of the starting character in the substring; if
343     /// the index is npos or greater than the length of the string then the
344     /// empty substring will be returned.
345     ///
346     /// \param End - The index following the last character to include in the
347     /// substring. If this is npos, or less than \arg Start, or exceeds the
348     /// number of characters remaining in the string, the string suffix
349     /// (starting with \arg Start) will be returned.
350     StringRef slice(size_t Start, size_t End) const {
351       Start = min(Start, Length);
352       End = min(max(Start, End), Length);
353       return StringRef(Data + Start, End - Start);
354     }
355
356     /// split - Split into two substrings around the first occurrence of a
357     /// separator character.
358     ///
359     /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
360     /// such that (*this == LHS + Separator + RHS) is true and RHS is
361     /// maximal. If \arg Separator is not in the string, then the result is a
362     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
363     ///
364     /// \param Separator - The character to split on.
365     /// \return - The split substrings.
366     std::pair<StringRef, StringRef> split(char Separator) const {
367       size_t Idx = find(Separator);
368       if (Idx == npos)
369         return std::make_pair(*this, StringRef());
370       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
371     }
372
373     /// split - Split into two substrings around the first occurrence of a
374     /// separator string.
375     ///
376     /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
377     /// such that (*this == LHS + Separator + RHS) is true and RHS is
378     /// maximal. If \arg Separator is not in the string, then the result is a
379     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
380     ///
381     /// \param Separator - The string to split on.
382     /// \return - The split substrings.
383     std::pair<StringRef, StringRef> split(StringRef Separator) const {
384       size_t Idx = find(Separator);
385       if (Idx == npos)
386         return std::make_pair(*this, StringRef());
387       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
388     }
389
390     /// split - Split into substrings around the occurrences of a separator
391     /// string.
392     ///
393     /// Each substring is stored in \arg A. If \arg MaxSplit is >= 0, at most
394     /// \arg MaxSplit splits are done and consequently <= \arg MaxSplit
395     /// elements are added to A.
396     /// If \arg KeepEmpty is false, empty strings are not added to \arg A. They
397     /// still count when considering \arg MaxSplit
398     /// An useful invariant is that
399     /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
400     ///
401     /// \param A - Where to put the substrings.
402     /// \param Separator - The string to split on.
403     /// \param MaxSplit - The maximum number of times the string is split.
404     /// \param KeepEmpty - True if empty substring should be added.
405     void split(SmallVectorImpl<StringRef> &A,
406                StringRef Separator, int MaxSplit = -1,
407                bool KeepEmpty = true) const;
408
409     /// rsplit - Split into two substrings around the last occurrence of a
410     /// separator character.
411     ///
412     /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
413     /// such that (*this == LHS + Separator + RHS) is true and RHS is
414     /// minimal. If \arg Separator is not in the string, then the result is a
415     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
416     ///
417     /// \param Separator - The character to split on.
418     /// \return - The split substrings.
419     std::pair<StringRef, StringRef> rsplit(char Separator) const {
420       size_t Idx = rfind(Separator);
421       if (Idx == npos)
422         return std::make_pair(*this, StringRef());
423       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
424     }
425
426     /// @}
427   };
428
429   /// @name StringRef Comparison Operators
430   /// @{
431
432   inline bool operator==(StringRef LHS, StringRef RHS) {
433     return LHS.equals(RHS);
434   }
435
436   inline bool operator!=(StringRef LHS, StringRef RHS) {
437     return !(LHS == RHS);
438   }
439
440   inline bool operator<(StringRef LHS, StringRef RHS) {
441     return LHS.compare(RHS) == -1;
442   }
443
444   inline bool operator<=(StringRef LHS, StringRef RHS) {
445     return LHS.compare(RHS) != 1;
446   }
447
448   inline bool operator>(StringRef LHS, StringRef RHS) {
449     return LHS.compare(RHS) == 1;
450   }
451
452   inline bool operator>=(StringRef LHS, StringRef RHS) {
453     return LHS.compare(RHS) != -1;
454   }
455
456   /// @}
457
458   // StringRefs can be treated like a POD type.
459   template <typename T> struct isPodLike;
460   template <> struct isPodLike<StringRef> { static const bool value = true; };
461
462 }
463
464 #endif