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;
23 /// StringRef - Represent a constant reference to a string, i.e. a character
24 /// array and a length, which need not be null terminated.
26 /// This class does not own the string data, it is expected to be used in
27 /// situations where the character data resides in some other buffer, whose
28 /// lifetime extends past that of the StringRef. For this reason, it is not in
29 /// general safe to store a StringRef.
32 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;
38 /// The start of the string, in an external buffer.
41 /// The length of the string.
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; }
51 /// @name Constructors
54 /// Construct an empty string ref.
55 /*implicit*/ StringRef() : Data(0), Length(0) {}
57 /// Construct a string ref from a cstring.
58 /*implicit*/ StringRef(const char *Str)
59 : Data(Str), Length(::strlen(Str)) {}
61 /// Construct a string ref from a pointer and length.
62 /*implicit*/ StringRef(const char *data, size_t length)
63 : Data(data), Length(length) {}
65 /// Construct a string ref from an std::string.
66 /*implicit*/ StringRef(const std::string &Str)
67 : Data(Str.data()), Length(Str.length()) {}
73 iterator begin() const { return Data; }
75 iterator end() const { return Data + Length; }
78 /// @name String Operations
81 /// data - Get a pointer to the start of the string (which may not be null
83 const char *data() const { return Data; }
85 /// empty - Check if the string is empty.
86 bool empty() const { return Length == 0; }
88 /// size - Get the string size.
89 size_t size() const { return Length; }
91 /// front - Get the first character in the string.
97 /// back - Get the last character in the string.
100 return Data[Length-1];
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);
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;
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;
122 // Otherwise the prefixes match, so we only need to check the lengths.
123 if (Length == RHS.Length)
125 return Length < RHS.Length ? -1 : 1;
128 /// compare_lower - Compare two strings, ignoring case.
129 int compare_lower(StringRef RHS) const;
131 /// compare_numeric - Compare two strings, treating sequences of digits as
133 int compare_numeric(StringRef RHS) const;
135 /// \brief Determine the edit distance between this string and another
138 /// \param Other the string to compare this string against.
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
145 /// \returns the minimum number of character insertions, removals,
146 /// or (if \p AllowReplacements is \c true) replacements needed to
147 /// transform one of the given strings into the other. If zero,
148 /// the strings are identical.
149 unsigned edit_distance(StringRef Other, bool AllowReplacements = true);
151 /// str - Get the contents as an std::string.
152 std::string str() const { return std::string(Data, Length); }
155 /// @name Operator Overloads
158 char operator[](size_t Index) const {
159 assert(Index < Length && "Invalid index!");
164 /// @name Type Conversions
167 operator std::string() const {
172 /// @name String Predicates
175 /// startswith - Check if this string starts with the given \arg Prefix.
176 bool startswith(StringRef Prefix) const {
177 return Length >= Prefix.Length &&
178 memcmp(Data, Prefix.Data, Prefix.Length) == 0;
181 /// endswith - Check if this string ends with the given \arg Suffix.
182 bool endswith(StringRef Suffix) const {
183 return Length >= Suffix.Length &&
184 memcmp(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
188 /// @name String Searching
191 /// find - Search for the first character \arg C in the string.
193 /// \return - The index of the first occurrence of \arg C, or npos if not
195 size_t find(char C, size_t From = 0) const {
196 for (size_t i = min(From, Length), e = Length; i != e; ++i)
202 /// find - Search for the first string \arg Str in the string.
204 /// \return - The index of the first occurrence of \arg Str, or npos if not
206 size_t find(StringRef Str, size_t From = 0) const;
208 /// rfind - Search for the last character \arg C in the string.
210 /// \return - The index of the last occurrence of \arg C, or npos if not
212 size_t rfind(char C, size_t From = npos) const {
213 From = min(From, Length);
223 /// rfind - Search for the last string \arg Str in the string.
225 /// \return - The index of the last occurrence of \arg Str, or npos if not
227 size_t rfind(StringRef Str) const;
229 /// find_first_of - Find the first character in the string that is \arg C,
230 /// or npos if not found. Same as find.
231 size_type find_first_of(char C, size_t = 0) const { return find(C); }
233 /// find_first_of - Find the first character in the string that is in \arg
234 /// Chars, or npos if not found.
236 /// Note: O(size() * Chars.size())
237 size_type find_first_of(StringRef Chars, size_t From = 0) const;
239 /// find_first_not_of - Find the first character in the string that is not
240 /// \arg C or npos if not found.
241 size_type find_first_not_of(char C, size_t From = 0) const;
243 /// find_first_not_of - Find the first character in the string that is not
244 /// in the string \arg Chars, or npos if not found.
246 /// Note: O(size() * Chars.size())
247 size_type find_first_not_of(StringRef Chars, size_t From = 0) const;
250 /// @name Helpful Algorithms
253 /// count - Return the number of occurrences of \arg C in the string.
254 size_t count(char C) const {
256 for (size_t i = 0, e = Length; i != e; ++i)
262 /// count - Return the number of non-overlapped occurrences of \arg Str in
264 size_t count(StringRef Str) const;
266 /// getAsInteger - Parse the current string as an integer of the specified
267 /// radix. If Radix is specified as zero, this does radix autosensing using
268 /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
270 /// If the string is invalid or if only a subset of the string is valid,
271 /// this returns true to signify the error. The string is considered
272 /// erroneous if empty.
274 bool getAsInteger(unsigned Radix, long long &Result) const;
275 bool getAsInteger(unsigned Radix, unsigned long long &Result) const;
276 bool getAsInteger(unsigned Radix, int &Result) const;
277 bool getAsInteger(unsigned Radix, unsigned &Result) const;
279 // TODO: Provide overloads for int/unsigned that check for overflow.
281 /// getAsInteger - Parse the current string as an integer of the
282 /// specified radix, or of an autosensed radix if the radix given
283 /// is 0. The current value in Result is discarded, and the
284 /// storage is changed to be wide enough to store the parsed
287 /// Returns true if the string does not solely consist of a valid
288 /// non-empty number in the appropriate base.
290 /// APInt::fromString is superficially similar but assumes the
291 /// string is well-formed in the given radix.
292 bool getAsInteger(unsigned Radix, APInt &Result) const;
295 /// @name Substring Operations
298 /// substr - Return a reference to the substring from [Start, Start + N).
300 /// \param Start - The index of the starting character in the substring; if
301 /// the index is npos or greater than the length of the string then the
302 /// empty substring will be returned.
304 /// \param N - The number of characters to included in the substring. If N
305 /// exceeds the number of characters remaining in the string, the string
306 /// suffix (starting with \arg Start) will be returned.
307 StringRef substr(size_t Start, size_t N = npos) const {
308 Start = min(Start, Length);
309 return StringRef(Data + Start, min(N, Length - Start));
312 /// slice - Return a reference to the substring from [Start, End).
314 /// \param Start - The index of the starting character in the substring; if
315 /// the index is npos or greater than the length of the string then the
316 /// empty substring will be returned.
318 /// \param End - The index following the last character to include in the
319 /// substring. If this is npos, or less than \arg Start, or exceeds the
320 /// number of characters remaining in the string, the string suffix
321 /// (starting with \arg Start) will be returned.
322 StringRef slice(size_t Start, size_t End) const {
323 Start = min(Start, Length);
324 End = min(max(Start, End), Length);
325 return StringRef(Data + Start, End - Start);
328 /// split - Split into two substrings around the first occurrence of a
329 /// separator character.
331 /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
332 /// such that (*this == LHS + Separator + RHS) is true and RHS is
333 /// maximal. If \arg Separator is not in the string, then the result is a
334 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
336 /// \param Separator - The character to split on.
337 /// \return - The split substrings.
338 std::pair<StringRef, StringRef> split(char Separator) const {
339 size_t Idx = find(Separator);
341 return std::make_pair(*this, StringRef());
342 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
345 /// split - Split into two substrings around the first occurrence of a
346 /// separator string.
348 /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
349 /// such that (*this == LHS + Separator + RHS) is true and RHS is
350 /// maximal. If \arg Separator is not in the string, then the result is a
351 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
353 /// \param Separator - The string to split on.
354 /// \return - The split substrings.
355 std::pair<StringRef, StringRef> split(StringRef Separator) const {
356 size_t Idx = find(Separator);
358 return std::make_pair(*this, StringRef());
359 return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
362 /// split - Split into substrings around the occurrences of a separator
365 /// Each substring is stored in \arg A. If \arg MaxSplit is >= 0, at most
366 /// \arg MaxSplit splits are done and consequently <= \arg MaxSplit
367 /// elements are added to A.
368 /// If \arg KeepEmpty is false, empty strings are not added to \arg A. They
369 /// still count when considering \arg MaxSplit
370 /// An useful invariant is that
371 /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
373 /// \param A - Where to put the substrings.
374 /// \param Separator - The string to split on.
375 /// \param MaxSplit - The maximum number of times the string is split.
376 /// \param KeepEmpty - True if empty substring should be added.
377 void split(SmallVectorImpl<StringRef> &A,
378 StringRef Separator, int MaxSplit = -1,
379 bool KeepEmpty = true) const;
381 /// rsplit - Split into two substrings around the last occurrence of a
382 /// separator character.
384 /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
385 /// such that (*this == LHS + Separator + RHS) is true and RHS is
386 /// minimal. If \arg Separator is not in the string, then the result is a
387 /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
389 /// \param Separator - The character to split on.
390 /// \return - The split substrings.
391 std::pair<StringRef, StringRef> rsplit(char Separator) const {
392 size_t Idx = rfind(Separator);
394 return std::make_pair(*this, StringRef());
395 return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
401 /// @name StringRef Comparison Operators
404 inline bool operator==(StringRef LHS, StringRef RHS) {
405 return LHS.equals(RHS);
408 inline bool operator!=(StringRef LHS, StringRef RHS) {
409 return !(LHS == RHS);
412 inline bool operator<(StringRef LHS, StringRef RHS) {
413 return LHS.compare(RHS) == -1;
416 inline bool operator<=(StringRef LHS, StringRef RHS) {
417 return LHS.compare(RHS) != 1;
420 inline bool operator>(StringRef LHS, StringRef RHS) {
421 return LHS.compare(RHS) == 1;
424 inline bool operator>=(StringRef LHS, StringRef RHS) {
425 return LHS.compare(RHS) != -1;