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