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