1 //===--- StringRef.h - Constant String Reference Wrapper --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_ADT_STRINGREF_H
11 #define LLVM_ADT_STRINGREF_H
20 class SmallVectorImpl;
22 /// StringRef - Represent a constant reference to a string, i.e. a character
23 /// array and a length, which need not be null terminated.
25 /// This class does not own the string data, it is expected to be used in
26 /// situations where the character data resides in some other buffer, whose
27 /// lifetime extends past that of the StringRef. For this reason, it is not in
28 /// general safe to store a StringRef.
31 typedef const char *iterator;
32 typedef const char *const_iterator;
33 static const size_t npos = ~size_t(0);
34 typedef size_t size_type;
37 /// The start of the string, in an external buffer.
40 /// The length of the string.
43 // Workaround PR5482: nearly all gcc 4.x miscompile StringRef and std::min()
44 // Changing the arg of min to be an integer, instead of a reference to an
45 // integer works around this bug.
46 size_t min(size_t a, size_t b) const { return a < b ? a : b; }
47 size_t max(size_t a, size_t b) const { return a > b ? a : b; }
50 /// @name Constructors
53 /// Construct an empty string ref.
54 /*implicit*/ StringRef() : Data(0), Length(0) {}
56 /// Construct a string ref from a cstring.
57 /*implicit*/ StringRef(const char *Str)
58 : Data(Str), Length(::strlen(Str)) {}
60 /// Construct a string ref from a pointer and length.
61 /*implicit*/ StringRef(const char *data, size_t length)
62 : Data(data), Length(length) {}
64 /// Construct a string ref from an std::string.
65 /*implicit*/ StringRef(const std::string &Str)
66 : Data(Str.data()), Length(Str.length()) {}
72 iterator begin() const { return Data; }
74 iterator end() const { return Data + Length; }
77 /// @name String Operations
80 /// data - Get a pointer to the start of the string (which may not be null
82 const char *data() const { return Data; }
84 /// empty - Check if the string is empty.
85 bool empty() const { return Length == 0; }
87 /// size - Get the string size.
88 size_t size() const { return Length; }
90 /// front - Get the first character in the string.
96 /// back - Get the last character in the string.
99 return Data[Length-1];
102 /// equals - Check for string equality, this is more efficient than
103 /// compare() when the relative ordering of inequal strings isn't needed.
104 bool equals(StringRef RHS) const {
105 return (Length == RHS.Length &&
106 memcmp(Data, RHS.Data, RHS.Length) == 0);
109 /// equals_lower - Check for string equality, ignoring case.
110 bool equals_lower(StringRef RHS) const {
111 return Length == RHS.Length && compare_lower(RHS) == 0;
114 /// compare - Compare two strings; the result is -1, 0, or 1 if this string
115 /// is lexicographically less than, equal to, or greater than the \arg RHS.
116 int compare(StringRef RHS) const {
117 // Check the prefix for a mismatch.
118 if (int Res = memcmp(Data, RHS.Data, min(Length, RHS.Length)))
119 return Res < 0 ? -1 : 1;
121 // Otherwise the prefixes match, so we only need to check the lengths.
122 if (Length == RHS.Length)
124 return Length < RHS.Length ? -1 : 1;
127 /// compare_lower - Compare two strings, ignoring case.
128 int compare_lower(StringRef RHS) const;
130 /// \brief Determine the edit distance between this string and another
133 /// \param Other the string to compare this string against.
135 /// \param AllowReplacements whether to allow character
136 /// replacements (change one character into another) as a single
137 /// operation, rather than as two operations (an insertion and a
140 /// \returns the minimum number of character insertions, removals,
141 /// or (if \p AllowReplacements is \c true) replacements needed to
142 /// transform one of the given strings into the other. If zero,
143 /// the strings are identical.
144 unsigned edit_distance(StringRef Other, bool AllowReplacements = true);
146 /// str - Get the contents as an std::string.
147 std::string str() const { return std::string(Data, Length); }
150 /// @name Operator Overloads
153 char operator[](size_t Index) const {
154 assert(Index < Length && "Invalid index!");
159 /// @name Type Conversions
162 operator std::string() const {
167 /// @name String Predicates
170 /// startswith - Check if this string starts with the given \arg Prefix.
171 bool startswith(StringRef Prefix) const {
172 return Length >= Prefix.Length &&
173 memcmp(Data, Prefix.Data, Prefix.Length) == 0;
176 /// endswith - Check if this string ends with the given \arg Suffix.
177 bool endswith(StringRef Suffix) const {
178 return Length >= Suffix.Length &&
179 memcmp(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
183 /// @name String Searching
186 /// find - Search for the first character \arg C in the string.
188 /// \return - The index of the first occurrence of \arg C, or npos if not
190 size_t find(char C, size_t From = 0) const {
191 for (size_t i = min(From, Length), e = Length; i != e; ++i)
197 /// find - Search for the first string \arg Str in the string.
199 /// \return - The index of the first occurrence of \arg Str, or npos if not
201 size_t find(StringRef Str, size_t From = 0) const;
203 /// rfind - Search for the last character \arg C in the string.
205 /// \return - The index of the last occurrence of \arg C, or npos if not
207 size_t rfind(char C, size_t From = npos) const {
208 From = min(From, Length);
218 /// rfind - Search for the last string \arg Str in the string.
220 /// \return - The index of the last occurrence of \arg Str, or npos if not
222 size_t rfind(StringRef Str) const;
224 /// find_first_of - Find the first character in the string that is \arg C,
225 /// or npos if not found. Same as find.
226 size_type find_first_of(char C, size_t = 0) const { return find(C); }
228 /// find_first_of - Find the first character in the string that is in \arg
229 /// Chars, or npos if not found.
231 /// Note: O(size() * Chars.size())
232 size_type find_first_of(StringRef Chars, size_t From = 0) const;
234 /// find_first_not_of - Find the first character in the string that is not
235 /// \arg C or npos if not found.
236 size_type find_first_not_of(char C, size_t From = 0) const;
238 /// find_first_not_of - Find the first character in the string that is not
239 /// in the string \arg Chars, or npos if not found.
241 /// Note: O(size() * Chars.size())
242 size_type find_first_not_of(StringRef Chars, size_t From = 0) const;
245 /// @name Helpful Algorithms
248 /// count - Return the number of occurrences of \arg C in the string.
249 size_t count(char C) const {
251 for (size_t i = 0, e = Length; i != e; ++i)
257 /// count - Return the number of non-overlapped occurrences of \arg Str in
259 size_t count(StringRef Str) const;
261 /// getAsInteger - Parse the current string as an integer of the specified
262 /// radix. If Radix is specified as zero, this does radix autosensing using
263 /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
265 /// If the string is invalid or if only a subset of the string is valid,
266 /// this returns true to signify the error. The string is considered
267 /// erroneous if empty.
269 bool getAsInteger(unsigned Radix, long long &Result) const;
270 bool getAsInteger(unsigned Radix, unsigned long long &Result) const;
271 bool getAsInteger(unsigned Radix, int &Result) const;
272 bool getAsInteger(unsigned Radix, unsigned &Result) const;
274 // TODO: Provide overloads for int/unsigned that check for overflow.
277 /// @name Substring Operations
280 /// substr - Return a reference to the substring from [Start, Start + N).
282 /// \param Start - The index of the starting character in the substring; if
283 /// the index is npos or greater than the length of the string then the
284 /// empty substring will be returned.
286 /// \param N - The number of characters to included in the substring. If N
287 /// exceeds the number of characters remaining in the string, the string
288 /// suffix (starting with \arg Start) will be returned.
289 StringRef substr(size_t Start, size_t N = npos) const {
290 Start = min(Start, Length);
291 return StringRef(Data + Start, min(N, Length - Start));
294 /// slice - Return a reference to the substring from [Start, End).
296 /// \param Start - The index of the starting character in the substring; if
297 /// the index is npos or greater than the length of the string then the
298 /// empty substring will be returned.
300 /// \param End - The index following the last character to include in the
301 /// substring. If this is npos, or less than \arg Start, or exceeds the
302 /// number of characters remaining in the string, the string suffix
303 /// (starting with \arg Start) will be returned.
304 StringRef slice(size_t Start, size_t End) const {
305 Start = min(Start, Length);
306 End = min(max(Start, End), Length);
307 return StringRef(Data + Start, End - Start);
310 /// split - Split into two substrings around the first occurrence of a
311 /// separator character.
313 /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
314 /// such that (*this == LHS + Separator + RHS) is true and RHS is
315 /// maximal. If \arg Separator is not in the string, then the result is a
316 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
318 /// \param Separator - The character to split on.
319 /// \return - The split substrings.
320 std::pair<StringRef, StringRef> split(char Separator) const {
321 size_t Idx = find(Separator);
323 return std::make_pair(*this, StringRef());
324 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
327 /// split - Split into two substrings around the first occurrence of a
328 /// separator string.
330 /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
331 /// such that (*this == LHS + Separator + RHS) is true and RHS is
332 /// maximal. If \arg Separator is not in the string, then the result is a
333 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
335 /// \param Separator - The string to split on.
336 /// \return - The split substrings.
337 std::pair<StringRef, StringRef> split(StringRef Separator) const {
338 size_t Idx = find(Separator);
340 return std::make_pair(*this, StringRef());
341 return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
344 /// split - Split into substrings around the occurrences of a separator
347 /// Each substring is stored in \arg A. If \arg MaxSplit is >= 0, at most
348 /// \arg MaxSplit splits are done and consequently <= \arg MaxSplit
349 /// elements are added to A.
350 /// If \arg KeepEmpty is false, empty strings are not added to \arg A. They
351 /// still count when considering \arg MaxSplit
352 /// An useful invariant is that
353 /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
355 /// \param A - Where to put the substrings.
356 /// \param Separator - The string to split on.
357 /// \param MaxSplit - The maximum number of times the string is split.
358 /// \parm KeepEmpty - True if empty substring should be added.
359 void split(SmallVectorImpl<StringRef> &A,
360 StringRef Separator, int MaxSplit = -1,
361 bool KeepEmpty = true) const;
363 /// rsplit - Split into two substrings around the last occurrence of a
364 /// separator character.
366 /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
367 /// such that (*this == LHS + Separator + RHS) is true and RHS is
368 /// minimal. If \arg Separator is not in the string, then the result is a
369 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
371 /// \param Separator - The character to split on.
372 /// \return - The split substrings.
373 std::pair<StringRef, StringRef> rsplit(char Separator) const {
374 size_t Idx = rfind(Separator);
376 return std::make_pair(*this, StringRef());
377 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
383 /// @name StringRef Comparison Operators
386 inline bool operator==(StringRef LHS, StringRef RHS) {
387 return LHS.equals(RHS);
390 inline bool operator!=(StringRef LHS, StringRef RHS) {
391 return !(LHS == RHS);
394 inline bool operator<(StringRef LHS, StringRef RHS) {
395 return LHS.compare(RHS) == -1;
398 inline bool operator<=(StringRef LHS, StringRef RHS) {
399 return LHS.compare(RHS) != 1;
402 inline bool operator>(StringRef LHS, StringRef RHS) {
403 return LHS.compare(RHS) == 1;
406 inline bool operator>=(StringRef LHS, StringRef RHS) {
407 return LHS.compare(RHS) != -1;