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