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/OwningPtr.h"
17 // MSVC emits references to this into the translation units which reference it.
19 const size_t StringRef::npos;
22 static char ascii_tolower(char x) {
23 if (x >= 'A' && x <= 'Z')
28 static bool ascii_isdigit(char x) {
29 return x >= '0' && x <= '9';
32 /// compare_lower - Compare strings, ignoring case.
33 int StringRef::compare_lower(StringRef RHS) const {
34 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
35 unsigned char LHC = ascii_tolower(Data[I]);
36 unsigned char RHC = ascii_tolower(RHS.Data[I]);
38 return LHC < RHC ? -1 : 1;
41 if (Length == RHS.Length)
43 return Length < RHS.Length ? -1 : 1;
46 /// compare_numeric - Compare strings, handle embedded numbers.
47 int StringRef::compare_numeric(StringRef RHS) const {
48 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
49 // Check for sequences of digits.
50 if (ascii_isdigit(Data[I]) && ascii_isdigit(RHS.Data[I])) {
51 // The longer sequence of numbers is considered larger.
52 // This doesn't really handle prefixed zeros well.
54 for (J = I + 1; J != E + 1; ++J) {
55 bool ld = J < Length && ascii_isdigit(Data[J]);
56 bool rd = J < RHS.Length && ascii_isdigit(RHS.Data[J]);
62 // The two number sequences have the same length (J-I), just memcmp them.
63 if (int Res = compareMemory(Data + I, RHS.Data + I, J - I))
64 return Res < 0 ? -1 : 1;
65 // Identical number sequences, continue search after the numbers.
69 if (Data[I] != RHS.Data[I])
70 return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1;
72 if (Length == RHS.Length)
74 return Length < RHS.Length ? -1 : 1;
77 // Compute the edit distance between the two given strings.
78 unsigned StringRef::edit_distance(llvm::StringRef Other,
79 bool AllowReplacements,
80 unsigned MaxEditDistance) {
81 // The algorithm implemented below is the "classic"
82 // dynamic-programming algorithm for computing the Levenshtein
83 // distance, which is described here:
85 // http://en.wikipedia.org/wiki/Levenshtein_distance
87 // Although the algorithm is typically described using an m x n
88 // array, only two rows are used at a time, so this implemenation
89 // just keeps two separate vectors for those two rows.
91 size_type n = Other.size();
93 const unsigned SmallBufferSize = 64;
94 unsigned SmallBuffer[SmallBufferSize];
95 llvm::OwningArrayPtr<unsigned> Allocated;
96 unsigned *previous = SmallBuffer;
97 if (2*(n + 1) > SmallBufferSize) {
98 previous = new unsigned [2*(n+1)];
99 Allocated.reset(previous);
101 unsigned *current = previous + (n + 1);
103 for (unsigned i = 0; i <= n; ++i)
106 for (size_type y = 1; y <= m; ++y) {
108 unsigned BestThisRow = current[0];
110 for (size_type x = 1; x <= n; ++x) {
111 if (AllowReplacements) {
112 current[x] = min(previous[x-1] + ((*this)[y-1] == Other[x-1]? 0u:1u),
113 min(current[x-1], previous[x])+1);
116 if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1];
117 else current[x] = min(current[x-1], previous[x]) + 1;
119 BestThisRow = min(BestThisRow, current[x]);
122 if (MaxEditDistance && BestThisRow > MaxEditDistance)
123 return MaxEditDistance + 1;
125 unsigned *tmp = current;
130 unsigned Result = previous[n];
134 //===----------------------------------------------------------------------===//
136 //===----------------------------------------------------------------------===//
139 /// find - Search for the first string \arg Str in the string.
141 /// \return - The index of the first occurrence of \arg Str, or npos if not
143 size_t StringRef::find(StringRef Str, size_t From) const {
144 size_t N = Str.size();
148 // For short haystacks or unsupported needles fall back to the naive algorithm
149 if (Length < 16 || N > 255 || N == 0) {
150 for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
151 if (substr(i, N).equals(Str))
156 // Build the bad char heuristic table, with uint8_t to reduce cache thrashing.
157 uint8_t BadCharSkip[256];
158 std::memset(BadCharSkip, N, 256);
159 for (unsigned i = 0; i != N-1; ++i)
160 BadCharSkip[(uint8_t)Str[i]] = N-1-i;
162 unsigned Len = Length, Pos = min(From, Length);
164 if (substr(Pos, N).equals(Str)) // See if this is the correct substring.
167 // Otherwise skip the appropriate number of bytes.
168 uint8_t Skip = BadCharSkip[(uint8_t)Data[Pos+N-1]];
176 /// rfind - Search for the last string \arg Str in the string.
178 /// \return - The index of the last occurrence of \arg Str, or npos if not
180 size_t StringRef::rfind(StringRef Str) const {
181 size_t N = Str.size();
184 for (size_t i = Length - N + 1, e = 0; i != e;) {
186 if (substr(i, N).equals(Str))
192 /// find_first_of - Find the first character in the string that is in \arg
193 /// Chars, or npos if not found.
195 /// Note: O(size() + Chars.size())
196 StringRef::size_type StringRef::find_first_of(StringRef Chars,
198 std::bitset<1 << CHAR_BIT> CharBits;
199 for (size_type i = 0; i != Chars.size(); ++i)
200 CharBits.set((unsigned char)Chars[i]);
202 for (size_type i = min(From, Length), e = Length; i != e; ++i)
203 if (CharBits.test((unsigned char)Data[i]))
208 /// find_first_not_of - Find the first character in the string that is not
209 /// \arg C or npos if not found.
210 StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
211 for (size_type i = min(From, Length), e = Length; i != e; ++i)
217 /// find_first_not_of - Find the first character in the string that is not
218 /// in the string \arg Chars, or npos if not found.
220 /// Note: O(size() + Chars.size())
221 StringRef::size_type StringRef::find_first_not_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), e = Length; i != e; ++i)
228 if (!CharBits.test((unsigned char)Data[i]))
233 /// find_last_of - Find the last character in the string that is in \arg C,
234 /// or npos if not found.
236 /// Note: O(size() + Chars.size())
237 StringRef::size_type StringRef::find_last_of(StringRef Chars,
239 std::bitset<1 << CHAR_BIT> CharBits;
240 for (size_type i = 0; i != Chars.size(); ++i)
241 CharBits.set((unsigned char)Chars[i]);
243 for (size_type i = min(From, Length) - 1, e = -1; i != e; --i)
244 if (CharBits.test((unsigned char)Data[i]))
249 //===----------------------------------------------------------------------===//
250 // Helpful Algorithms
251 //===----------------------------------------------------------------------===//
253 /// count - Return the number of non-overlapped occurrences of \arg Str in
255 size_t StringRef::count(StringRef Str) const {
257 size_t N = Str.size();
260 for (size_t i = 0, e = Length - N + 1; i != e; ++i)
261 if (substr(i, N).equals(Str))
266 static unsigned GetAutoSenseRadix(StringRef &Str) {
267 if (Str.startswith("0x")) {
270 } else if (Str.startswith("0b")) {
273 } else if (Str.startswith("0")) {
281 /// GetAsUnsignedInteger - Workhorse method that converts a integer character
282 /// sequence of radix up to 36 to an unsigned long long value.
283 static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix,
284 unsigned long long &Result) {
285 // Autosense radix if not specified.
287 Radix = GetAutoSenseRadix(Str);
289 // Empty strings (after the radix autosense) are invalid.
290 if (Str.empty()) return true;
292 // Parse all the bytes of the string given this radix. Watch for overflow.
294 while (!Str.empty()) {
296 if (Str[0] >= '0' && Str[0] <= '9')
297 CharVal = Str[0]-'0';
298 else if (Str[0] >= 'a' && Str[0] <= 'z')
299 CharVal = Str[0]-'a'+10;
300 else if (Str[0] >= 'A' && Str[0] <= 'Z')
301 CharVal = Str[0]-'A'+10;
305 // If the parsed value is larger than the integer radix, the string is
307 if (CharVal >= Radix)
310 // Add in this character.
311 unsigned long long PrevResult = Result;
312 Result = Result*Radix+CharVal;
314 // Check for overflow.
315 if (Result < PrevResult)
324 bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const {
325 return GetAsUnsignedInteger(*this, Radix, Result);
329 bool StringRef::getAsInteger(unsigned Radix, long long &Result) const {
330 unsigned long long ULLVal;
332 // Handle positive strings first.
333 if (empty() || front() != '-') {
334 if (GetAsUnsignedInteger(*this, Radix, ULLVal) ||
335 // Check for value so large it overflows a signed value.
336 (long long)ULLVal < 0)
342 // Get the positive part of the value.
343 if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) ||
344 // Reject values so large they'd overflow as negative signed, but allow
345 // "-0". This negates the unsigned so that the negative isn't undefined
346 // on signed overflow.
347 (long long)-ULLVal > 0)
354 bool StringRef::getAsInteger(unsigned Radix, int &Result) const {
356 if (getAsInteger(Radix, Val) ||
363 bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const {
364 unsigned long long Val;
365 if (getAsInteger(Radix, Val) ||
366 (unsigned)Val != Val)
372 bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
373 StringRef Str = *this;
375 // Autosense radix if not specified.
377 Radix = GetAutoSenseRadix(Str);
379 assert(Radix > 1 && Radix <= 36);
381 // Empty strings (after the radix autosense) are invalid.
382 if (Str.empty()) return true;
384 // Skip leading zeroes. This can be a significant improvement if
385 // it means we don't need > 64 bits.
386 while (!Str.empty() && Str.front() == '0')
389 // If it was nothing but zeroes....
391 Result = APInt(64, 0);
395 // (Over-)estimate the required number of bits.
396 unsigned Log2Radix = 0;
397 while ((1U << Log2Radix) < Radix) Log2Radix++;
398 bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
400 unsigned BitWidth = Log2Radix * Str.size();
401 if (BitWidth < Result.getBitWidth())
402 BitWidth = Result.getBitWidth(); // don't shrink the result
404 Result = Result.zext(BitWidth);
406 APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix
407 if (!IsPowerOf2Radix) {
408 // These must have the same bit-width as Result.
409 RadixAP = APInt(BitWidth, Radix);
410 CharAP = APInt(BitWidth, 0);
413 // Parse all the bytes of the string given this radix.
415 while (!Str.empty()) {
417 if (Str[0] >= '0' && Str[0] <= '9')
418 CharVal = Str[0]-'0';
419 else if (Str[0] >= 'a' && Str[0] <= 'z')
420 CharVal = Str[0]-'a'+10;
421 else if (Str[0] >= 'A' && Str[0] <= 'Z')
422 CharVal = Str[0]-'A'+10;
426 // If the parsed value is larger than the integer radix, the string is
428 if (CharVal >= Radix)
431 // Add in this character.
432 if (IsPowerOf2Radix) {
433 Result <<= Log2Radix;