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 - 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;
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))
50 return Length < RHS.Length ? -1 : 1;
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]);
59 return LHC < RHC ? -1 : 1;
62 if (Length == RHS.Length)
64 return Length < RHS.Length ? -1 : 1;
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])
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]);
84 return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1;
86 if (Length == RHS.Length)
88 return Length < RHS.Length ? -1 : 1;
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:
99 // http://en.wikipedia.org/wiki/Levenshtein_distance
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();
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);
115 unsigned *current = previous + (n + 1);
117 for (unsigned i = 0; i <= n; ++i)
120 for (size_type y = 1; y <= m; ++y) {
122 unsigned BestThisRow = current[0];
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);
130 if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1];
131 else current[x] = min(current[x-1], previous[x]) + 1;
133 BestThisRow = min(BestThisRow, current[x]);
136 if (MaxEditDistance && BestThisRow > MaxEditDistance)
137 return MaxEditDistance + 1;
139 unsigned *tmp = current;
144 unsigned Result = previous[n];
148 //===----------------------------------------------------------------------===//
150 //===----------------------------------------------------------------------===//
153 /// find - Search for the first string \arg Str in the string.
155 /// \return - The index of the first occurrence of \arg Str, or npos if not
157 size_t StringRef::find(StringRef Str, size_t From) const {
158 size_t N = Str.size();
161 for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
162 if (substr(i, N).equals(Str))
167 /// rfind - Search for the last string \arg Str in the string.
169 /// \return - The index of the last occurrence of \arg Str, or npos if not
171 size_t StringRef::rfind(StringRef Str) const {
172 size_t N = Str.size();
175 for (size_t i = Length - N + 1, e = 0; i != e;) {
177 if (substr(i, N).equals(Str))
183 /// find_first_of - Find the first character in the string that is in \arg
184 /// Chars, or npos if not found.
186 /// Note: O(size() + Chars.size())
187 StringRef::size_type StringRef::find_first_of(StringRef Chars,
189 std::bitset<1 << CHAR_BIT> CharBits;
190 for (size_type i = 0; i != Chars.size(); ++i)
191 CharBits.set((unsigned char)Chars[i]);
193 for (size_type i = min(From, Length), e = Length; i != e; ++i)
194 if (CharBits.test((unsigned char)Data[i]))
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)
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.
211 /// Note: O(size() + Chars.size())
212 StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
214 std::bitset<1 << CHAR_BIT> CharBits;
215 for (size_type i = 0; i != Chars.size(); ++i)
216 CharBits.set((unsigned char)Chars[i]);
218 for (size_type i = min(From, Length), e = Length; i != e; ++i)
219 if (!CharBits.test((unsigned char)Data[i]))
224 /// find_last_of - Find the last character in the string that is in \arg C,
225 /// or npos if not found.
227 /// Note: O(size() + Chars.size())
228 StringRef::size_type StringRef::find_last_of(StringRef Chars,
230 std::bitset<1 << CHAR_BIT> CharBits;
231 for (size_type i = 0; i != Chars.size(); ++i)
232 CharBits.set((unsigned char)Chars[i]);
234 for (size_type i = min(From, Length) - 1, e = -1; i != e; --i)
235 if (CharBits.test((unsigned char)Data[i]))
240 //===----------------------------------------------------------------------===//
241 // Helpful Algorithms
242 //===----------------------------------------------------------------------===//
244 /// count - Return the number of non-overlapped occurrences of \arg Str in
246 size_t StringRef::count(StringRef Str) const {
248 size_t N = Str.size();
251 for (size_t i = 0, e = Length - N + 1; i != e; ++i)
252 if (substr(i, N).equals(Str))
257 static unsigned GetAutoSenseRadix(StringRef &Str) {
258 if (Str.startswith("0x")) {
261 } else if (Str.startswith("0b")) {
264 } else if (Str.startswith("0")) {
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.
278 Radix = GetAutoSenseRadix(Str);
280 // Empty strings (after the radix autosense) are invalid.
281 if (Str.empty()) return true;
283 // Parse all the bytes of the string given this radix. Watch for overflow.
285 while (!Str.empty()) {
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;
296 // If the parsed value is larger than the integer radix, the string is
298 if (CharVal >= Radix)
301 // Add in this character.
302 unsigned long long PrevResult = Result;
303 Result = Result*Radix+CharVal;
305 // Check for overflow.
306 if (Result < PrevResult)
315 bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const {
316 return GetAsUnsignedInteger(*this, Radix, Result);
320 bool StringRef::getAsInteger(unsigned Radix, long long &Result) const {
321 unsigned long long ULLVal;
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)
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)
345 bool StringRef::getAsInteger(unsigned Radix, int &Result) const {
347 if (getAsInteger(Radix, Val) ||
354 bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const {
355 unsigned long long Val;
356 if (getAsInteger(Radix, Val) ||
357 (unsigned)Val != Val)
363 bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
364 StringRef Str = *this;
366 // Autosense radix if not specified.
368 Radix = GetAutoSenseRadix(Str);
370 assert(Radix > 1 && Radix <= 36);
372 // Empty strings (after the radix autosense) are invalid.
373 if (Str.empty()) return true;
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')
380 // If it was nothing but zeroes....
382 Result = APInt(64, 0);
386 // (Over-)estimate the required number of bits.
387 unsigned Log2Radix = 0;
388 while ((1U << Log2Radix) < Radix) Log2Radix++;
389 bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
391 unsigned BitWidth = Log2Radix * Str.size();
392 if (BitWidth < Result.getBitWidth())
393 BitWidth = Result.getBitWidth(); // don't shrink the result
395 Result = Result.zext(BitWidth);
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);
404 // Parse all the bytes of the string given this radix.
406 while (!Str.empty()) {
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;
417 // If the parsed value is larger than the integer radix, the string is
419 if (CharVal >= Radix)
422 // Add in this character.
423 if (IsPowerOf2Radix) {
424 Result <<= Log2Radix;