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