1 //===-- StringRef.cpp - Lightweight String References ---------------------===//
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 #include "llvm/ADT/StringRef.h"
11 #include "llvm/ADT/APInt.h"
12 #include "llvm/ADT/Hashing.h"
13 #include "llvm/ADT/OwningPtr.h"
14 #include "llvm/ADT/edit_distance.h"
19 // MSVC emits references to this into the translation units which reference it.
21 const size_t StringRef::npos;
24 static char ascii_tolower(char x) {
25 if (x >= 'A' && x <= 'Z')
30 static char ascii_toupper(char x) {
31 if (x >= 'a' && x <= 'z')
36 static bool ascii_isdigit(char x) {
37 return x >= '0' && x <= '9';
40 /// compare_lower - Compare strings, ignoring case.
41 int StringRef::compare_lower(StringRef RHS) const {
42 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
43 unsigned char LHC = ascii_tolower(Data[I]);
44 unsigned char RHC = ascii_tolower(RHS.Data[I]);
46 return LHC < RHC ? -1 : 1;
49 if (Length == RHS.Length)
51 return Length < RHS.Length ? -1 : 1;
54 /// compare_numeric - Compare strings, handle embedded numbers.
55 int StringRef::compare_numeric(StringRef RHS) const {
56 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
57 // Check for sequences of digits.
58 if (ascii_isdigit(Data[I]) && ascii_isdigit(RHS.Data[I])) {
59 // The longer sequence of numbers is considered larger.
60 // This doesn't really handle prefixed zeros well.
62 for (J = I + 1; J != E + 1; ++J) {
63 bool ld = J < Length && ascii_isdigit(Data[J]);
64 bool rd = J < RHS.Length && ascii_isdigit(RHS.Data[J]);
70 // The two number sequences have the same length (J-I), just memcmp them.
71 if (int Res = compareMemory(Data + I, RHS.Data + I, J - I))
72 return Res < 0 ? -1 : 1;
73 // Identical number sequences, continue search after the numbers.
77 if (Data[I] != RHS.Data[I])
78 return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1;
80 if (Length == RHS.Length)
82 return Length < RHS.Length ? -1 : 1;
85 // Compute the edit distance between the two given strings.
86 unsigned StringRef::edit_distance(llvm::StringRef Other,
87 bool AllowReplacements,
88 unsigned MaxEditDistance) {
89 return llvm::ComputeEditDistance(
90 llvm::ArrayRef<char>(data(), size()),
91 llvm::ArrayRef<char>(Other.data(), Other.size()),
92 AllowReplacements, MaxEditDistance);
95 //===----------------------------------------------------------------------===//
97 //===----------------------------------------------------------------------===//
99 std::string StringRef::lower() const {
100 std::string Result(size(), char());
101 for (size_type i = 0, e = size(); i != e; ++i) {
102 Result[i] = ascii_tolower(Data[i]);
107 std::string StringRef::upper() const {
108 std::string Result(size(), char());
109 for (size_type i = 0, e = size(); i != e; ++i) {
110 Result[i] = ascii_toupper(Data[i]);
115 //===----------------------------------------------------------------------===//
117 //===----------------------------------------------------------------------===//
120 /// find - Search for the first string \arg Str in the string.
122 /// \return - The index of the first occurrence of \arg Str, or npos if not
124 size_t StringRef::find(StringRef Str, size_t From) const {
125 size_t N = Str.size();
129 // For short haystacks or unsupported needles fall back to the naive algorithm
130 if (Length < 16 || N > 255 || N == 0) {
131 for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
132 if (substr(i, N).equals(Str))
140 // Build the bad char heuristic table, with uint8_t to reduce cache thrashing.
141 uint8_t BadCharSkip[256];
142 std::memset(BadCharSkip, N, 256);
143 for (unsigned i = 0; i != N-1; ++i)
144 BadCharSkip[(uint8_t)Str[i]] = N-1-i;
146 unsigned Len = Length-From, Pos = From;
148 if (substr(Pos, N).equals(Str)) // See if this is the correct substring.
151 // Otherwise skip the appropriate number of bytes.
152 uint8_t Skip = BadCharSkip[(uint8_t)(*this)[Pos+N-1]];
160 /// rfind - Search for the last string \arg Str in the string.
162 /// \return - The index of the last occurrence of \arg Str, or npos if not
164 size_t StringRef::rfind(StringRef Str) const {
165 size_t N = Str.size();
168 for (size_t i = Length - N + 1, e = 0; i != e;) {
170 if (substr(i, N).equals(Str))
176 /// find_first_of - Find the first character in the string that is in \arg
177 /// Chars, or npos if not found.
179 /// Note: O(size() + Chars.size())
180 StringRef::size_type StringRef::find_first_of(StringRef Chars,
182 std::bitset<1 << CHAR_BIT> CharBits;
183 for (size_type i = 0; i != Chars.size(); ++i)
184 CharBits.set((unsigned char)Chars[i]);
186 for (size_type i = min(From, Length), e = Length; i != e; ++i)
187 if (CharBits.test((unsigned char)Data[i]))
192 /// find_first_not_of - Find the first character in the string that is not
193 /// \arg C or npos if not found.
194 StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
195 for (size_type i = min(From, Length), e = Length; i != e; ++i)
201 /// find_first_not_of - Find the first character in the string that is not
202 /// in the string \arg Chars, or npos if not found.
204 /// Note: O(size() + Chars.size())
205 StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
207 std::bitset<1 << CHAR_BIT> CharBits;
208 for (size_type i = 0; i != Chars.size(); ++i)
209 CharBits.set((unsigned char)Chars[i]);
211 for (size_type i = min(From, Length), e = Length; i != e; ++i)
212 if (!CharBits.test((unsigned char)Data[i]))
217 /// find_last_of - Find the last character in the string that is in \arg C,
218 /// or npos if not found.
220 /// Note: O(size() + Chars.size())
221 StringRef::size_type StringRef::find_last_of(StringRef Chars,
223 std::bitset<1 << CHAR_BIT> CharBits;
224 for (size_type i = 0; i != Chars.size(); ++i)
225 CharBits.set((unsigned char)Chars[i]);
227 for (size_type i = min(From, Length) - 1, e = -1; i != e; --i)
228 if (CharBits.test((unsigned char)Data[i]))
233 /// find_last_not_of - Find the last character in the string that is not
234 /// \arg C, or npos if not found.
235 StringRef::size_type StringRef::find_last_not_of(char C, size_t From) const {
236 for (size_type i = min(From, Length) - 1, e = -1; i != e; --i)
242 /// find_last_not_of - Find the last character in the string that is not in
243 /// \arg Chars, or npos if not found.
245 /// Note: O(size() + Chars.size())
246 StringRef::size_type StringRef::find_last_not_of(StringRef Chars,
248 std::bitset<1 << CHAR_BIT> CharBits;
249 for (size_type i = 0, e = Chars.size(); i != e; ++i)
250 CharBits.set((unsigned char)Chars[i]);
252 for (size_type i = min(From, Length) - 1, e = -1; i != e; --i)
253 if (!CharBits.test((unsigned char)Data[i]))
258 void StringRef::split(SmallVectorImpl<StringRef> &A,
259 StringRef Separators, int MaxSplit,
260 bool KeepEmpty) const {
261 StringRef rest = *this;
263 // rest.data() is used to distinguish cases like "a," that splits into
264 // "a" + "" and "a" that splits into "a" + 0.
266 rest.data() != NULL && (MaxSplit < 0 || splits < MaxSplit);
268 std::pair<StringRef, StringRef> p = rest.split(Separators);
270 if (KeepEmpty || p.first.size() != 0)
271 A.push_back(p.first);
274 // If we have a tail left, add it.
275 if (rest.data() != NULL && (rest.size() != 0 || KeepEmpty))
279 //===----------------------------------------------------------------------===//
280 // Helpful Algorithms
281 //===----------------------------------------------------------------------===//
283 /// count - Return the number of non-overlapped occurrences of \arg Str in
285 size_t StringRef::count(StringRef Str) const {
287 size_t N = Str.size();
290 for (size_t i = 0, e = Length - N + 1; i != e; ++i)
291 if (substr(i, N).equals(Str))
296 static unsigned GetAutoSenseRadix(StringRef &Str) {
297 if (Str.startswith("0x")) {
302 if (Str.startswith("0b")) {
307 if (Str.startswith("0o")) {
312 if (Str.startswith("0"))
319 /// GetAsUnsignedInteger - Workhorse method that converts a integer character
320 /// sequence of radix up to 36 to an unsigned long long value.
321 bool llvm::getAsUnsignedInteger(StringRef Str, unsigned Radix,
322 unsigned long long &Result) {
323 // Autosense radix if not specified.
325 Radix = GetAutoSenseRadix(Str);
327 // Empty strings (after the radix autosense) are invalid.
328 if (Str.empty()) return true;
330 // Parse all the bytes of the string given this radix. Watch for overflow.
332 while (!Str.empty()) {
334 if (Str[0] >= '0' && Str[0] <= '9')
335 CharVal = Str[0]-'0';
336 else if (Str[0] >= 'a' && Str[0] <= 'z')
337 CharVal = Str[0]-'a'+10;
338 else if (Str[0] >= 'A' && Str[0] <= 'Z')
339 CharVal = Str[0]-'A'+10;
343 // If the parsed value is larger than the integer radix, the string is
345 if (CharVal >= Radix)
348 // Add in this character.
349 unsigned long long PrevResult = Result;
350 Result = Result*Radix+CharVal;
352 // Check for overflow by shifting back and seeing if bits were lost.
353 if (Result/Radix < PrevResult)
362 bool llvm::getAsSignedInteger(StringRef Str, unsigned Radix,
364 unsigned long long ULLVal;
366 // Handle positive strings first.
367 if (Str.empty() || Str.front() != '-') {
368 if (getAsUnsignedInteger(Str, Radix, ULLVal) ||
369 // Check for value so large it overflows a signed value.
370 (long long)ULLVal < 0)
376 // Get the positive part of the value.
377 if (getAsUnsignedInteger(Str.substr(1), Radix, ULLVal) ||
378 // Reject values so large they'd overflow as negative signed, but allow
379 // "-0". This negates the unsigned so that the negative isn't undefined
380 // on signed overflow.
381 (long long)-ULLVal > 0)
388 bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
389 StringRef Str = *this;
391 // Autosense radix if not specified.
393 Radix = GetAutoSenseRadix(Str);
395 assert(Radix > 1 && Radix <= 36);
397 // Empty strings (after the radix autosense) are invalid.
398 if (Str.empty()) return true;
400 // Skip leading zeroes. This can be a significant improvement if
401 // it means we don't need > 64 bits.
402 while (!Str.empty() && Str.front() == '0')
405 // If it was nothing but zeroes....
407 Result = APInt(64, 0);
411 // (Over-)estimate the required number of bits.
412 unsigned Log2Radix = 0;
413 while ((1U << Log2Radix) < Radix) Log2Radix++;
414 bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
416 unsigned BitWidth = Log2Radix * Str.size();
417 if (BitWidth < Result.getBitWidth())
418 BitWidth = Result.getBitWidth(); // don't shrink the result
419 else if (BitWidth > Result.getBitWidth())
420 Result = Result.zext(BitWidth);
422 APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix
423 if (!IsPowerOf2Radix) {
424 // These must have the same bit-width as Result.
425 RadixAP = APInt(BitWidth, Radix);
426 CharAP = APInt(BitWidth, 0);
429 // Parse all the bytes of the string given this radix.
431 while (!Str.empty()) {
433 if (Str[0] >= '0' && Str[0] <= '9')
434 CharVal = Str[0]-'0';
435 else if (Str[0] >= 'a' && Str[0] <= 'z')
436 CharVal = Str[0]-'a'+10;
437 else if (Str[0] >= 'A' && Str[0] <= 'Z')
438 CharVal = Str[0]-'A'+10;
442 // If the parsed value is larger than the integer radix, the string is
444 if (CharVal >= Radix)
447 // Add in this character.
448 if (IsPowerOf2Radix) {
449 Result <<= Log2Radix;
464 // Implementation of StringRef hashing.
465 hash_code llvm::hash_value(StringRef S) {
466 return hash_combine_range(S.begin(), S.end());