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