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