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 if (Data[I] == RHS.Data[I])
51 if (ascii_isdigit(Data[I]) && ascii_isdigit(RHS.Data[I])) {
52 // The longer sequence of numbers is larger. This doesn't really handle
53 // prefixed zeros well.
54 for (size_t 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]);
63 return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1;
65 if (Length == RHS.Length)
67 return Length < RHS.Length ? -1 : 1;
70 // Compute the edit distance between the two given strings.
71 unsigned StringRef::edit_distance(llvm::StringRef Other,
72 bool AllowReplacements,
73 unsigned MaxEditDistance) {
74 // The algorithm implemented below is the "classic"
75 // dynamic-programming algorithm for computing the Levenshtein
76 // distance, which is described here:
78 // http://en.wikipedia.org/wiki/Levenshtein_distance
80 // Although the algorithm is typically described using an m x n
81 // array, only two rows are used at a time, so this implemenation
82 // just keeps two separate vectors for those two rows.
84 size_type n = Other.size();
86 const unsigned SmallBufferSize = 64;
87 unsigned SmallBuffer[SmallBufferSize];
88 llvm::OwningArrayPtr<unsigned> Allocated;
89 unsigned *previous = SmallBuffer;
90 if (2*(n + 1) > SmallBufferSize) {
91 previous = new unsigned [2*(n+1)];
92 Allocated.reset(previous);
94 unsigned *current = previous + (n + 1);
96 for (unsigned i = 0; i <= n; ++i)
99 for (size_type y = 1; y <= m; ++y) {
101 unsigned BestThisRow = current[0];
103 for (size_type x = 1; x <= n; ++x) {
104 if (AllowReplacements) {
105 current[x] = min(previous[x-1] + ((*this)[y-1] == Other[x-1]? 0u:1u),
106 min(current[x-1], previous[x])+1);
109 if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1];
110 else current[x] = min(current[x-1], previous[x]) + 1;
112 BestThisRow = min(BestThisRow, current[x]);
115 if (MaxEditDistance && BestThisRow > MaxEditDistance)
116 return MaxEditDistance + 1;
118 unsigned *tmp = current;
123 unsigned Result = previous[n];
127 //===----------------------------------------------------------------------===//
129 //===----------------------------------------------------------------------===//
132 /// find - Search for the first string \arg Str in the string.
134 /// \return - The index of the first occurence of \arg Str, or npos if not
136 size_t StringRef::find(StringRef Str, size_t From) const {
137 size_t N = Str.size();
140 for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
141 if (substr(i, N).equals(Str))
146 /// rfind - Search for the last string \arg Str in the string.
148 /// \return - The index of the last occurence of \arg Str, or npos if not
150 size_t StringRef::rfind(StringRef Str) const {
151 size_t N = Str.size();
154 for (size_t i = Length - N + 1, e = 0; i != e;) {
156 if (substr(i, N).equals(Str))
162 /// find_first_of - Find the first character in the string that is in \arg
163 /// Chars, or npos if not found.
165 /// Note: O(size() + Chars.size())
166 StringRef::size_type StringRef::find_first_of(StringRef Chars,
168 std::bitset<1 << CHAR_BIT> CharBits;
169 for (size_type i = 0; i != Chars.size(); ++i)
170 CharBits.set((unsigned char)Chars[i]);
172 for (size_type i = min(From, Length), e = Length; i != e; ++i)
173 if (CharBits.test((unsigned char)Data[i]))
178 /// find_first_not_of - Find the first character in the string that is not
179 /// \arg C or npos if not found.
180 StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
181 for (size_type i = min(From, Length), e = Length; i != e; ++i)
187 /// find_first_not_of - Find the first character in the string that is not
188 /// in the string \arg Chars, or npos if not found.
190 /// Note: O(size() + Chars.size())
191 StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
193 std::bitset<1 << CHAR_BIT> CharBits;
194 for (size_type i = 0; i != Chars.size(); ++i)
195 CharBits.set((unsigned char)Chars[i]);
197 for (size_type i = min(From, Length), e = Length; i != e; ++i)
198 if (!CharBits.test((unsigned char)Data[i]))
204 //===----------------------------------------------------------------------===//
205 // Helpful Algorithms
206 //===----------------------------------------------------------------------===//
208 /// count - Return the number of non-overlapped occurrences of \arg Str in
210 size_t StringRef::count(StringRef Str) const {
212 size_t N = Str.size();
215 for (size_t i = 0, e = Length - N + 1; i != e; ++i)
216 if (substr(i, N).equals(Str))
221 static unsigned GetAutoSenseRadix(StringRef &Str) {
222 if (Str.startswith("0x")) {
225 } else if (Str.startswith("0b")) {
228 } else if (Str.startswith("0")) {
236 /// GetAsUnsignedInteger - Workhorse method that converts a integer character
237 /// sequence of radix up to 36 to an unsigned long long value.
238 static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix,
239 unsigned long long &Result) {
240 // Autosense radix if not specified.
242 Radix = GetAutoSenseRadix(Str);
244 // Empty strings (after the radix autosense) are invalid.
245 if (Str.empty()) return true;
247 // Parse all the bytes of the string given this radix. Watch for overflow.
249 while (!Str.empty()) {
251 if (Str[0] >= '0' && Str[0] <= '9')
252 CharVal = Str[0]-'0';
253 else if (Str[0] >= 'a' && Str[0] <= 'z')
254 CharVal = Str[0]-'a'+10;
255 else if (Str[0] >= 'A' && Str[0] <= 'Z')
256 CharVal = Str[0]-'A'+10;
260 // If the parsed value is larger than the integer radix, the string is
262 if (CharVal >= Radix)
265 // Add in this character.
266 unsigned long long PrevResult = Result;
267 Result = Result*Radix+CharVal;
269 // Check for overflow.
270 if (Result < PrevResult)
279 bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const {
280 return GetAsUnsignedInteger(*this, Radix, Result);
284 bool StringRef::getAsInteger(unsigned Radix, long long &Result) const {
285 unsigned long long ULLVal;
287 // Handle positive strings first.
288 if (empty() || front() != '-') {
289 if (GetAsUnsignedInteger(*this, Radix, ULLVal) ||
290 // Check for value so large it overflows a signed value.
291 (long long)ULLVal < 0)
297 // Get the positive part of the value.
298 if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) ||
299 // Reject values so large they'd overflow as negative signed, but allow
300 // "-0". This negates the unsigned so that the negative isn't undefined
301 // on signed overflow.
302 (long long)-ULLVal > 0)
309 bool StringRef::getAsInteger(unsigned Radix, int &Result) const {
311 if (getAsInteger(Radix, Val) ||
318 bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const {
319 unsigned long long Val;
320 if (getAsInteger(Radix, Val) ||
321 (unsigned)Val != Val)
327 bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
328 StringRef Str = *this;
330 // Autosense radix if not specified.
332 Radix = GetAutoSenseRadix(Str);
334 assert(Radix > 1 && Radix <= 36);
336 // Empty strings (after the radix autosense) are invalid.
337 if (Str.empty()) return true;
339 // Skip leading zeroes. This can be a significant improvement if
340 // it means we don't need > 64 bits.
341 while (!Str.empty() && Str.front() == '0')
344 // If it was nothing but zeroes....
346 Result = APInt(64, 0);
350 // (Over-)estimate the required number of bits.
351 unsigned Log2Radix = 0;
352 while ((1U << Log2Radix) < Radix) Log2Radix++;
353 bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
355 unsigned BitWidth = Log2Radix * Str.size();
356 if (BitWidth < Result.getBitWidth())
357 BitWidth = Result.getBitWidth(); // don't shrink the result
359 Result.zext(BitWidth);
361 APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix
362 if (!IsPowerOf2Radix) {
363 // These must have the same bit-width as Result.
364 RadixAP = APInt(BitWidth, Radix);
365 CharAP = APInt(BitWidth, 0);
368 // Parse all the bytes of the string given this radix.
370 while (!Str.empty()) {
372 if (Str[0] >= '0' && Str[0] <= '9')
373 CharVal = Str[0]-'0';
374 else if (Str[0] >= 'a' && Str[0] <= 'z')
375 CharVal = Str[0]-'a'+10;
376 else if (Str[0] >= 'A' && Str[0] <= 'Z')
377 CharVal = Str[0]-'A'+10;
381 // If the parsed value is larger than the integer radix, the string is
383 if (CharVal >= Radix)
386 // Add in this character.
387 if (IsPowerOf2Radix) {
388 Result <<= Log2Radix;