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"
16 // MSVC emits references to this into the translation units which reference it.
18 const size_t StringRef::npos;
21 static char ascii_tolower(char x) {
22 if (x >= 'A' && x <= 'Z')
27 static bool ascii_isdigit(char x) {
28 return x >= '0' && x <= '9';
31 /// compare_lower - Compare strings, ignoring case.
32 int StringRef::compare_lower(StringRef RHS) const {
33 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
34 unsigned char LHC = ascii_tolower(Data[I]);
35 unsigned char RHC = ascii_tolower(RHS.Data[I]);
37 return LHC < RHC ? -1 : 1;
40 if (Length == RHS.Length)
42 return Length < RHS.Length ? -1 : 1;
45 /// compare_numeric - Compare strings, handle embedded numbers.
46 int StringRef::compare_numeric(StringRef RHS) const {
47 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
48 if (Data[I] == RHS.Data[I])
50 if (ascii_isdigit(Data[I]) && ascii_isdigit(RHS.Data[I])) {
51 // The longer sequence of numbers is larger. This doesn't really handle
52 // prefixed zeros well.
53 for (size_t J = I+1; J != E+1; ++J) {
54 bool ld = J < Length && ascii_isdigit(Data[J]);
55 bool rd = J < RHS.Length && ascii_isdigit(RHS.Data[J]);
62 return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1;
64 if (Length == RHS.Length)
66 return Length < RHS.Length ? -1 : 1;
69 // Compute the edit distance between the two given strings.
70 unsigned StringRef::edit_distance(llvm::StringRef Other,
71 bool AllowReplacements,
72 unsigned MaxEditDistance) {
73 // The algorithm implemented below is the "classic"
74 // dynamic-programming algorithm for computing the Levenshtein
75 // distance, which is described here:
77 // http://en.wikipedia.org/wiki/Levenshtein_distance
79 // Although the algorithm is typically described using an m x n
80 // array, only two rows are used at a time, so this implemenation
81 // just keeps two separate vectors for those two rows.
83 size_type n = Other.size();
85 const unsigned SmallBufferSize = 64;
86 unsigned SmallBuffer[SmallBufferSize];
87 unsigned *Allocated = 0;
88 unsigned *previous = SmallBuffer;
89 if (2*(n + 1) > SmallBufferSize)
90 Allocated = previous = new unsigned [2*(n+1)];
91 unsigned *current = previous + (n + 1);
93 for (unsigned i = 0; i <= n; ++i)
96 for (size_type y = 1; y <= m; ++y) {
98 unsigned BestThisRow = current[0];
100 for (size_type x = 1; x <= n; ++x) {
101 if (AllowReplacements) {
102 current[x] = min(previous[x-1] + ((*this)[y-1] == Other[x-1]? 0u:1u),
103 min(current[x-1], previous[x])+1);
106 if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1];
107 else current[x] = min(current[x-1], previous[x]) + 1;
109 BestThisRow = min(BestThisRow, current[x]);
112 if (MaxEditDistance && BestThisRow > MaxEditDistance)
113 return MaxEditDistance + 1;
115 unsigned *tmp = current;
120 unsigned Result = previous[n];
126 //===----------------------------------------------------------------------===//
128 //===----------------------------------------------------------------------===//
131 /// find - Search for the first string \arg Str in the string.
133 /// \return - The index of the first occurence of \arg Str, or npos if not
135 size_t StringRef::find(StringRef Str, size_t From) const {
136 size_t N = Str.size();
139 for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
140 if (substr(i, N).equals(Str))
145 /// rfind - Search for the last string \arg Str in the string.
147 /// \return - The index of the last occurence of \arg Str, or npos if not
149 size_t StringRef::rfind(StringRef Str) const {
150 size_t N = Str.size();
153 for (size_t i = Length - N + 1, e = 0; i != e;) {
155 if (substr(i, N).equals(Str))
161 /// find_first_of - Find the first character in the string that is in \arg
162 /// Chars, or npos if not found.
164 /// Note: O(size() + Chars.size())
165 StringRef::size_type StringRef::find_first_of(StringRef Chars,
167 std::bitset<1 << CHAR_BIT> CharBits;
168 for (size_type i = 0; i != Chars.size(); ++i)
169 CharBits.set((unsigned char)Chars[i]);
171 for (size_type i = min(From, Length), e = Length; i != e; ++i)
172 if (CharBits.test((unsigned char)Data[i]))
177 /// find_first_not_of - Find the first character in the string that is not
178 /// \arg C or npos if not found.
179 StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
180 for (size_type i = min(From, Length), e = Length; i != e; ++i)
186 /// find_first_not_of - Find the first character in the string that is not
187 /// in the string \arg Chars, or npos if not found.
189 /// Note: O(size() + Chars.size())
190 StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
192 std::bitset<1 << CHAR_BIT> CharBits;
193 for (size_type i = 0; i != Chars.size(); ++i)
194 CharBits.set((unsigned char)Chars[i]);
196 for (size_type i = min(From, Length), e = Length; i != e; ++i)
197 if (!CharBits.test((unsigned char)Data[i]))
203 //===----------------------------------------------------------------------===//
204 // Helpful Algorithms
205 //===----------------------------------------------------------------------===//
207 /// count - Return the number of non-overlapped occurrences of \arg Str in
209 size_t StringRef::count(StringRef Str) const {
211 size_t N = Str.size();
214 for (size_t i = 0, e = Length - N + 1; i != e; ++i)
215 if (substr(i, N).equals(Str))
220 static unsigned GetAutoSenseRadix(StringRef &Str) {
221 if (Str.startswith("0x")) {
224 } else if (Str.startswith("0b")) {
227 } else if (Str.startswith("0")) {
235 /// GetAsUnsignedInteger - Workhorse method that converts a integer character
236 /// sequence of radix up to 36 to an unsigned long long value.
237 static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix,
238 unsigned long long &Result) {
239 // Autosense radix if not specified.
241 Radix = GetAutoSenseRadix(Str);
243 // Empty strings (after the radix autosense) are invalid.
244 if (Str.empty()) return true;
246 // Parse all the bytes of the string given this radix. Watch for overflow.
248 while (!Str.empty()) {
250 if (Str[0] >= '0' && Str[0] <= '9')
251 CharVal = Str[0]-'0';
252 else if (Str[0] >= 'a' && Str[0] <= 'z')
253 CharVal = Str[0]-'a'+10;
254 else if (Str[0] >= 'A' && Str[0] <= 'Z')
255 CharVal = Str[0]-'A'+10;
259 // If the parsed value is larger than the integer radix, the string is
261 if (CharVal >= Radix)
264 // Add in this character.
265 unsigned long long PrevResult = Result;
266 Result = Result*Radix+CharVal;
268 // Check for overflow.
269 if (Result < PrevResult)
278 bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const {
279 return GetAsUnsignedInteger(*this, Radix, Result);
283 bool StringRef::getAsInteger(unsigned Radix, long long &Result) const {
284 unsigned long long ULLVal;
286 // Handle positive strings first.
287 if (empty() || front() != '-') {
288 if (GetAsUnsignedInteger(*this, Radix, ULLVal) ||
289 // Check for value so large it overflows a signed value.
290 (long long)ULLVal < 0)
296 // Get the positive part of the value.
297 if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) ||
298 // Reject values so large they'd overflow as negative signed, but allow
299 // "-0". This negates the unsigned so that the negative isn't undefined
300 // on signed overflow.
301 (long long)-ULLVal > 0)
308 bool StringRef::getAsInteger(unsigned Radix, int &Result) const {
310 if (getAsInteger(Radix, Val) ||
317 bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const {
318 unsigned long long Val;
319 if (getAsInteger(Radix, Val) ||
320 (unsigned)Val != Val)
326 bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
327 StringRef Str = *this;
329 // Autosense radix if not specified.
331 Radix = GetAutoSenseRadix(Str);
333 assert(Radix > 1 && Radix <= 36);
335 // Empty strings (after the radix autosense) are invalid.
336 if (Str.empty()) return true;
338 // Skip leading zeroes. This can be a significant improvement if
339 // it means we don't need > 64 bits.
340 while (!Str.empty() && Str.front() == '0')
343 // If it was nothing but zeroes....
345 Result = APInt(64, 0);
349 // (Over-)estimate the required number of bits.
350 unsigned Log2Radix = 0;
351 while ((1U << Log2Radix) < Radix) Log2Radix++;
352 bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
354 unsigned BitWidth = Log2Radix * Str.size();
355 if (BitWidth < Result.getBitWidth())
356 BitWidth = Result.getBitWidth(); // don't shrink the result
358 Result.zext(BitWidth);
360 APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix
361 if (!IsPowerOf2Radix) {
362 // These must have the same bit-width as Result.
363 RadixAP = APInt(BitWidth, Radix);
364 CharAP = APInt(BitWidth, 0);
367 // Parse all the bytes of the string given this radix.
369 while (!Str.empty()) {
371 if (Str[0] >= '0' && Str[0] <= '9')
372 CharVal = Str[0]-'0';
373 else if (Str[0] >= 'a' && Str[0] <= 'z')
374 CharVal = Str[0]-'a'+10;
375 else if (Str[0] >= 'A' && Str[0] <= 'Z')
376 CharVal = Str[0]-'A'+10;
380 // If the parsed value is larger than the integer radix, the string is
382 if (CharVal >= Radix)
385 // Add in this character.
386 if (IsPowerOf2Radix) {
387 Result <<= Log2Radix;