Implements StringRef::compare with bounds. It is behaves similarly to strncmp()....
[oota-llvm.git] / lib / Support / StringRef.cpp
1 //===-- StringRef.cpp - Lightweight String References ---------------------===//
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 #include "llvm/ADT/StringRef.h"
11 #include "llvm/ADT/APInt.h"
12 #include "llvm/ADT/OwningPtr.h"
13 #include <bitset>
14
15 using namespace llvm;
16
17 // MSVC emits references to this into the translation units which reference it.
18 #ifndef _MSC_VER
19 const size_t StringRef::npos;
20 #endif
21
22 static char ascii_tolower(char x) {
23   if (x >= 'A' && x <= 'Z')
24     return x - 'A' + 'a';
25   return x;
26 }
27
28 static bool ascii_isdigit(char x) {
29   return x >= '0' && x <= '9';
30 }
31
32 /// compare - Compare two strings; the result is -1, 0, or 1 if this string
33 /// is lexicographically less than, equal to, or greater than the \arg RHS.
34 /// This is different than compare with no size specified as it only 
35 /// compares at most the first n bytes.
36 int StringRef::compare(StringRef RHS, size_t n) const {
37   // Check the prefix for a mismatch.
38   size_t maxToCmp = min(Length, RHS.Length);
39   maxToCmp = min(maxToCmp, n);
40   if (int Res = memcmp(Data, RHS.Data, maxToCmp))
41     return Res < 0 ? -1 : 1;
42   
43   // Otherwise the prefixes match, so we only need to check the lengths.
44   // Be mindful that if the n is less than or equal to the length of either
45   // string, that is the same as the strings matching because in that case
46   // we only care about the prefix.
47   if (((n <= Length) && (n <= RHS.Length)) || 
48       (Length == RHS.Length))
49     return 0;
50   return Length < RHS.Length ? -1 : 1;
51 }
52
53 /// compare_lower - Compare strings, ignoring case.
54 int StringRef::compare_lower(StringRef RHS) const {
55   for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
56     unsigned char LHC = ascii_tolower(Data[I]);
57     unsigned char RHC = ascii_tolower(RHS.Data[I]);
58     if (LHC != RHC)
59       return LHC < RHC ? -1 : 1;
60   }
61
62   if (Length == RHS.Length)
63     return 0;
64   return Length < RHS.Length ? -1 : 1;
65 }
66
67 /// compare_numeric - Compare strings, handle embedded numbers.
68 int StringRef::compare_numeric(StringRef RHS) const {
69   for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
70     if (Data[I] == RHS.Data[I])
71       continue;
72     if (ascii_isdigit(Data[I]) && ascii_isdigit(RHS.Data[I])) {
73       // The longer sequence of numbers is larger. This doesn't really handle
74       // prefixed zeros well.
75       for (size_t J = I+1; J != E+1; ++J) {
76         bool ld = J < Length && ascii_isdigit(Data[J]);
77         bool rd = J < RHS.Length && ascii_isdigit(RHS.Data[J]);
78         if (ld != rd)
79           return rd ? -1 : 1;
80         if (!rd)
81           break;
82       }
83     }
84     return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1;
85   }
86   if (Length == RHS.Length)
87     return 0;
88   return Length < RHS.Length ? -1 : 1;
89 }
90
91 // Compute the edit distance between the two given strings.
92 unsigned StringRef::edit_distance(llvm::StringRef Other,
93                                   bool AllowReplacements,
94                                   unsigned MaxEditDistance) {
95   // The algorithm implemented below is the "classic"
96   // dynamic-programming algorithm for computing the Levenshtein
97   // distance, which is described here:
98   //
99   //   http://en.wikipedia.org/wiki/Levenshtein_distance
100   //
101   // Although the algorithm is typically described using an m x n
102   // array, only two rows are used at a time, so this implemenation
103   // just keeps two separate vectors for those two rows.
104   size_type m = size();
105   size_type n = Other.size();
106
107   const unsigned SmallBufferSize = 64;
108   unsigned SmallBuffer[SmallBufferSize];
109   llvm::OwningArrayPtr<unsigned> Allocated;
110   unsigned *previous = SmallBuffer;
111   if (2*(n + 1) > SmallBufferSize) {
112     previous = new unsigned [2*(n+1)];
113     Allocated.reset(previous);
114   }
115   unsigned *current = previous + (n + 1);
116
117   for (unsigned i = 0; i <= n; ++i)
118     previous[i] = i;
119
120   for (size_type y = 1; y <= m; ++y) {
121     current[0] = y;
122     unsigned BestThisRow = current[0];
123
124     for (size_type x = 1; x <= n; ++x) {
125       if (AllowReplacements) {
126         current[x] = min(previous[x-1] + ((*this)[y-1] == Other[x-1]? 0u:1u),
127                          min(current[x-1], previous[x])+1);
128       }
129       else {
130         if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1];
131         else current[x] = min(current[x-1], previous[x]) + 1;
132       }
133       BestThisRow = min(BestThisRow, current[x]);
134     }
135
136     if (MaxEditDistance && BestThisRow > MaxEditDistance)
137       return MaxEditDistance + 1;
138
139     unsigned *tmp = current;
140     current = previous;
141     previous = tmp;
142   }
143
144   unsigned Result = previous[n];
145   return Result;
146 }
147
148 //===----------------------------------------------------------------------===//
149 // String Searching
150 //===----------------------------------------------------------------------===//
151
152
153 /// find - Search for the first string \arg Str in the string.
154 ///
155 /// \return - The index of the first occurrence of \arg Str, or npos if not
156 /// found.
157 size_t StringRef::find(StringRef Str, size_t From) const {
158   size_t N = Str.size();
159   if (N > Length)
160     return npos;
161   for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
162     if (substr(i, N).equals(Str))
163       return i;
164   return npos;
165 }
166
167 /// rfind - Search for the last string \arg Str in the string.
168 ///
169 /// \return - The index of the last occurrence of \arg Str, or npos if not
170 /// found.
171 size_t StringRef::rfind(StringRef Str) const {
172   size_t N = Str.size();
173   if (N > Length)
174     return npos;
175   for (size_t i = Length - N + 1, e = 0; i != e;) {
176     --i;
177     if (substr(i, N).equals(Str))
178       return i;
179   }
180   return npos;
181 }
182
183 /// find_first_of - Find the first character in the string that is in \arg
184 /// Chars, or npos if not found.
185 ///
186 /// Note: O(size() + Chars.size())
187 StringRef::size_type StringRef::find_first_of(StringRef Chars,
188                                               size_t From) const {
189   std::bitset<1 << CHAR_BIT> CharBits;
190   for (size_type i = 0; i != Chars.size(); ++i)
191     CharBits.set((unsigned char)Chars[i]);
192
193   for (size_type i = min(From, Length), e = Length; i != e; ++i)
194     if (CharBits.test((unsigned char)Data[i]))
195       return i;
196   return npos;
197 }
198
199 /// find_first_not_of - Find the first character in the string that is not
200 /// \arg C or npos if not found.
201 StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
202   for (size_type i = min(From, Length), e = Length; i != e; ++i)
203     if (Data[i] != C)
204       return i;
205   return npos;
206 }
207
208 /// find_first_not_of - Find the first character in the string that is not
209 /// in the string \arg Chars, or npos if not found.
210 ///
211 /// Note: O(size() + Chars.size())
212 StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
213                                                   size_t From) const {
214   std::bitset<1 << CHAR_BIT> CharBits;
215   for (size_type i = 0; i != Chars.size(); ++i)
216     CharBits.set((unsigned char)Chars[i]);
217
218   for (size_type i = min(From, Length), e = Length; i != e; ++i)
219     if (!CharBits.test((unsigned char)Data[i]))
220       return i;
221   return npos;
222 }
223
224 /// find_last_of - Find the last character in the string that is in \arg C,
225 /// or npos if not found.
226 ///
227 /// Note: O(size() + Chars.size())
228 StringRef::size_type StringRef::find_last_of(StringRef Chars,
229                                              size_t From) const {
230   std::bitset<1 << CHAR_BIT> CharBits;
231   for (size_type i = 0; i != Chars.size(); ++i)
232     CharBits.set((unsigned char)Chars[i]);
233
234   for (size_type i = min(From, Length) - 1, e = -1; i != e; --i)
235     if (CharBits.test((unsigned char)Data[i]))
236       return i;
237   return npos;
238 }
239
240 //===----------------------------------------------------------------------===//
241 // Helpful Algorithms
242 //===----------------------------------------------------------------------===//
243
244 /// count - Return the number of non-overlapped occurrences of \arg Str in
245 /// the string.
246 size_t StringRef::count(StringRef Str) const {
247   size_t Count = 0;
248   size_t N = Str.size();
249   if (N > Length)
250     return 0;
251   for (size_t i = 0, e = Length - N + 1; i != e; ++i)
252     if (substr(i, N).equals(Str))
253       ++Count;
254   return Count;
255 }
256
257 static unsigned GetAutoSenseRadix(StringRef &Str) {
258   if (Str.startswith("0x")) {
259     Str = Str.substr(2);
260     return 16;
261   } else if (Str.startswith("0b")) {
262     Str = Str.substr(2);
263     return 2;
264   } else if (Str.startswith("0")) {
265     return 8;
266   } else {
267     return 10;
268   }
269 }
270
271
272 /// GetAsUnsignedInteger - Workhorse method that converts a integer character
273 /// sequence of radix up to 36 to an unsigned long long value.
274 static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix,
275                                  unsigned long long &Result) {
276   // Autosense radix if not specified.
277   if (Radix == 0)
278     Radix = GetAutoSenseRadix(Str);
279
280   // Empty strings (after the radix autosense) are invalid.
281   if (Str.empty()) return true;
282
283   // Parse all the bytes of the string given this radix.  Watch for overflow.
284   Result = 0;
285   while (!Str.empty()) {
286     unsigned CharVal;
287     if (Str[0] >= '0' && Str[0] <= '9')
288       CharVal = Str[0]-'0';
289     else if (Str[0] >= 'a' && Str[0] <= 'z')
290       CharVal = Str[0]-'a'+10;
291     else if (Str[0] >= 'A' && Str[0] <= 'Z')
292       CharVal = Str[0]-'A'+10;
293     else
294       return true;
295
296     // If the parsed value is larger than the integer radix, the string is
297     // invalid.
298     if (CharVal >= Radix)
299       return true;
300
301     // Add in this character.
302     unsigned long long PrevResult = Result;
303     Result = Result*Radix+CharVal;
304
305     // Check for overflow.
306     if (Result < PrevResult)
307       return true;
308
309     Str = Str.substr(1);
310   }
311
312   return false;
313 }
314
315 bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const {
316   return GetAsUnsignedInteger(*this, Radix, Result);
317 }
318
319
320 bool StringRef::getAsInteger(unsigned Radix, long long &Result) const {
321   unsigned long long ULLVal;
322
323   // Handle positive strings first.
324   if (empty() || front() != '-') {
325     if (GetAsUnsignedInteger(*this, Radix, ULLVal) ||
326         // Check for value so large it overflows a signed value.
327         (long long)ULLVal < 0)
328       return true;
329     Result = ULLVal;
330     return false;
331   }
332
333   // Get the positive part of the value.
334   if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) ||
335       // Reject values so large they'd overflow as negative signed, but allow
336       // "-0".  This negates the unsigned so that the negative isn't undefined
337       // on signed overflow.
338       (long long)-ULLVal > 0)
339     return true;
340
341   Result = -ULLVal;
342   return false;
343 }
344
345 bool StringRef::getAsInteger(unsigned Radix, int &Result) const {
346   long long Val;
347   if (getAsInteger(Radix, Val) ||
348       (int)Val != Val)
349     return true;
350   Result = Val;
351   return false;
352 }
353
354 bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const {
355   unsigned long long Val;
356   if (getAsInteger(Radix, Val) ||
357       (unsigned)Val != Val)
358     return true;
359   Result = Val;
360   return false;
361 }
362
363 bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
364   StringRef Str = *this;
365
366   // Autosense radix if not specified.
367   if (Radix == 0)
368     Radix = GetAutoSenseRadix(Str);
369
370   assert(Radix > 1 && Radix <= 36);
371
372   // Empty strings (after the radix autosense) are invalid.
373   if (Str.empty()) return true;
374
375   // Skip leading zeroes.  This can be a significant improvement if
376   // it means we don't need > 64 bits.
377   while (!Str.empty() && Str.front() == '0')
378     Str = Str.substr(1);
379
380   // If it was nothing but zeroes....
381   if (Str.empty()) {
382     Result = APInt(64, 0);
383     return false;
384   }
385
386   // (Over-)estimate the required number of bits.
387   unsigned Log2Radix = 0;
388   while ((1U << Log2Radix) < Radix) Log2Radix++;
389   bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
390
391   unsigned BitWidth = Log2Radix * Str.size();
392   if (BitWidth < Result.getBitWidth())
393     BitWidth = Result.getBitWidth(); // don't shrink the result
394   else
395     Result = Result.zext(BitWidth);
396
397   APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix
398   if (!IsPowerOf2Radix) {
399     // These must have the same bit-width as Result.
400     RadixAP = APInt(BitWidth, Radix);
401     CharAP = APInt(BitWidth, 0);
402   }
403
404   // Parse all the bytes of the string given this radix.
405   Result = 0;
406   while (!Str.empty()) {
407     unsigned CharVal;
408     if (Str[0] >= '0' && Str[0] <= '9')
409       CharVal = Str[0]-'0';
410     else if (Str[0] >= 'a' && Str[0] <= 'z')
411       CharVal = Str[0]-'a'+10;
412     else if (Str[0] >= 'A' && Str[0] <= 'Z')
413       CharVal = Str[0]-'A'+10;
414     else
415       return true;
416
417     // If the parsed value is larger than the integer radix, the string is
418     // invalid.
419     if (CharVal >= Radix)
420       return true;
421
422     // Add in this character.
423     if (IsPowerOf2Radix) {
424       Result <<= Log2Radix;
425       Result |= CharVal;
426     } else {
427       Result *= RadixAP;
428       CharAP = CharVal;
429       Result += CharAP;
430     }
431
432     Str = Str.substr(1);
433   }
434
435   return false;
436 }