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