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