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"
13 #include "llvm/ADT/Hashing.h"
14 #include "llvm/ADT/edit_distance.h"
20 // MSVC emits references to this into the translation units which reference it.
22 const size_t StringRef::npos;
25 static char ascii_tolower(char x) {
26 if (x >= 'A' && x <= 'Z')
31 static char ascii_toupper(char x) {
32 if (x >= 'a' && x <= 'z')
37 static bool ascii_isdigit(char x) {
38 return x >= '0' && x <= '9';
41 /// compare_lower - Compare strings, ignoring case.
42 int StringRef::compare_lower(StringRef RHS) const {
43 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
44 unsigned char LHC = ascii_tolower(Data[I]);
45 unsigned char RHC = ascii_tolower(RHS.Data[I]);
47 return LHC < RHC ? -1 : 1;
50 if (Length == RHS.Length)
52 return Length < RHS.Length ? -1 : 1;
55 /// compare_numeric - Compare strings, handle embedded numbers.
56 int StringRef::compare_numeric(StringRef RHS) const {
57 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
58 // Check for sequences of digits.
59 if (ascii_isdigit(Data[I]) && ascii_isdigit(RHS.Data[I])) {
60 // The longer sequence of numbers is considered larger.
61 // This doesn't really handle prefixed zeros well.
63 for (J = I + 1; J != E + 1; ++J) {
64 bool ld = J < Length && ascii_isdigit(Data[J]);
65 bool rd = J < RHS.Length && ascii_isdigit(RHS.Data[J]);
71 // The two number sequences have the same length (J-I), just memcmp them.
72 if (int Res = compareMemory(Data + I, RHS.Data + I, J - I))
73 return Res < 0 ? -1 : 1;
74 // Identical number sequences, continue search after the numbers.
78 if (Data[I] != RHS.Data[I])
79 return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1;
81 if (Length == RHS.Length)
83 return Length < RHS.Length ? -1 : 1;
86 // Compute the edit distance between the two given strings.
87 unsigned StringRef::edit_distance(llvm::StringRef Other,
88 bool AllowReplacements,
89 unsigned MaxEditDistance) {
90 return llvm::ComputeEditDistance(
91 llvm::ArrayRef<char>(data(), size()),
92 llvm::ArrayRef<char>(Other.data(), Other.size()),
93 AllowReplacements, MaxEditDistance);
96 //===----------------------------------------------------------------------===//
98 //===----------------------------------------------------------------------===//
100 std::string StringRef::lower() const {
101 std::string Result(size(), char());
102 for (size_type i = 0, e = size(); i != e; ++i) {
103 Result[i] = ascii_tolower(Data[i]);
108 std::string StringRef::upper() const {
109 std::string Result(size(), char());
110 for (size_type i = 0, e = size(); i != e; ++i) {
111 Result[i] = ascii_toupper(Data[i]);
116 //===----------------------------------------------------------------------===//
118 //===----------------------------------------------------------------------===//
121 /// find - Search for the first string \arg Str in the string.
123 /// \return - The index of the first occurrence of \arg Str, or npos if not
125 size_t StringRef::find(StringRef Str, size_t From) const {
126 size_t N = Str.size();
130 // For short haystacks or unsupported needles fall back to the naive algorithm
131 if (Length < 16 || N > 255 || N == 0) {
132 for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
133 if (substr(i, N).equals(Str))
141 // Build the bad char heuristic table, with uint8_t to reduce cache thrashing.
142 uint8_t BadCharSkip[256];
143 std::memset(BadCharSkip, N, 256);
144 for (unsigned i = 0; i != N-1; ++i)
145 BadCharSkip[(uint8_t)Str[i]] = N-1-i;
147 unsigned Len = Length-From, Pos = From;
149 if (substr(Pos, N).equals(Str)) // See if this is the correct substring.
152 // Otherwise skip the appropriate number of bytes.
153 uint8_t Skip = BadCharSkip[(uint8_t)(*this)[Pos+N-1]];
161 /// rfind - Search for the last string \arg Str in the string.
163 /// \return - The index of the last occurrence of \arg Str, or npos if not
165 size_t StringRef::rfind(StringRef Str) const {
166 size_t N = Str.size();
169 for (size_t i = Length - N + 1, e = 0; i != e;) {
171 if (substr(i, N).equals(Str))
177 /// find_first_of - Find the first character in the string that is in \arg
178 /// Chars, or npos if not found.
180 /// Note: O(size() + Chars.size())
181 StringRef::size_type StringRef::find_first_of(StringRef Chars,
183 std::bitset<1 << CHAR_BIT> CharBits;
184 for (size_type i = 0; i != Chars.size(); ++i)
185 CharBits.set((unsigned char)Chars[i]);
187 for (size_type i = min(From, Length), e = Length; i != e; ++i)
188 if (CharBits.test((unsigned char)Data[i]))
193 /// find_first_not_of - Find the first character in the string that is not
194 /// \arg C or npos if not found.
195 StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
196 for (size_type i = min(From, Length), e = Length; i != e; ++i)
202 /// find_first_not_of - Find the first character in the string that is not
203 /// in the string \arg Chars, or npos if not found.
205 /// Note: O(size() + Chars.size())
206 StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
208 std::bitset<1 << CHAR_BIT> CharBits;
209 for (size_type i = 0; i != Chars.size(); ++i)
210 CharBits.set((unsigned char)Chars[i]);
212 for (size_type i = min(From, Length), e = Length; i != e; ++i)
213 if (!CharBits.test((unsigned char)Data[i]))
218 /// find_last_of - Find the last character in the string that is in \arg C,
219 /// or npos if not found.
221 /// Note: O(size() + Chars.size())
222 StringRef::size_type StringRef::find_last_of(StringRef Chars,
224 std::bitset<1 << CHAR_BIT> CharBits;
225 for (size_type i = 0; i != Chars.size(); ++i)
226 CharBits.set((unsigned char)Chars[i]);
228 for (size_type i = min(From, Length) - 1, e = -1; i != e; --i)
229 if (CharBits.test((unsigned char)Data[i]))
234 /// find_last_not_of - Find the last character in the string that is not
235 /// \arg C, or npos if not found.
236 StringRef::size_type StringRef::find_last_not_of(char C, size_t From) const {
237 for (size_type i = min(From, Length) - 1, e = -1; i != e; --i)
243 /// find_last_not_of - Find the last character in the string that is not in
244 /// \arg Chars, or npos if not found.
246 /// Note: O(size() + Chars.size())
247 StringRef::size_type StringRef::find_last_not_of(StringRef Chars,
249 std::bitset<1 << CHAR_BIT> CharBits;
250 for (size_type i = 0, e = Chars.size(); i != e; ++i)
251 CharBits.set((unsigned char)Chars[i]);
253 for (size_type i = min(From, Length) - 1, e = -1; i != e; --i)
254 if (!CharBits.test((unsigned char)Data[i]))
259 void StringRef::split(SmallVectorImpl<StringRef> &A,
260 StringRef Separators, int MaxSplit,
261 bool KeepEmpty) const {
262 StringRef rest = *this;
264 // rest.data() is used to distinguish cases like "a," that splits into
265 // "a" + "" and "a" that splits into "a" + 0.
267 rest.data() != NULL && (MaxSplit < 0 || splits < MaxSplit);
269 std::pair<StringRef, StringRef> p = rest.split(Separators);
271 if (KeepEmpty || p.first.size() != 0)
272 A.push_back(p.first);
275 // If we have a tail left, add it.
276 if (rest.data() != NULL && (rest.size() != 0 || KeepEmpty))
280 //===----------------------------------------------------------------------===//
281 // Helpful Algorithms
282 //===----------------------------------------------------------------------===//
284 /// count - Return the number of non-overlapped occurrences of \arg Str in
286 size_t StringRef::count(StringRef Str) const {
288 size_t N = Str.size();
291 for (size_t i = 0, e = Length - N + 1; i != e; ++i)
292 if (substr(i, N).equals(Str))
297 static unsigned GetAutoSenseRadix(StringRef &Str) {
298 if (Str.startswith("0x")) {
303 if (Str.startswith("0b")) {
308 if (Str.startswith("0o")) {
313 if (Str.startswith("0"))
320 /// GetAsUnsignedInteger - Workhorse method that converts a integer character
321 /// sequence of radix up to 36 to an unsigned long long value.
322 bool llvm::getAsUnsignedInteger(StringRef Str, unsigned Radix,
323 unsigned long long &Result) {
324 // Autosense radix if not specified.
326 Radix = GetAutoSenseRadix(Str);
328 // Empty strings (after the radix autosense) are invalid.
329 if (Str.empty()) return true;
331 // Parse all the bytes of the string given this radix. Watch for overflow.
333 while (!Str.empty()) {
335 if (Str[0] >= '0' && Str[0] <= '9')
336 CharVal = Str[0]-'0';
337 else if (Str[0] >= 'a' && Str[0] <= 'z')
338 CharVal = Str[0]-'a'+10;
339 else if (Str[0] >= 'A' && Str[0] <= 'Z')
340 CharVal = Str[0]-'A'+10;
344 // If the parsed value is larger than the integer radix, the string is
346 if (CharVal >= Radix)
349 // Add in this character.
350 unsigned long long PrevResult = Result;
351 Result = Result*Radix+CharVal;
353 // Check for overflow.
354 if (Result < PrevResult)
363 bool llvm::getAsSignedInteger(StringRef Str, unsigned Radix,
365 unsigned long long ULLVal;
367 // Handle positive strings first.
368 if (Str.empty() || Str.front() != '-') {
369 if (getAsUnsignedInteger(Str, Radix, ULLVal) ||
370 // Check for value so large it overflows a signed value.
371 (long long)ULLVal < 0)
377 // Get the positive part of the value.
378 if (getAsUnsignedInteger(Str.substr(1), Radix, ULLVal) ||
379 // Reject values so large they'd overflow as negative signed, but allow
380 // "-0". This negates the unsigned so that the negative isn't undefined
381 // on signed overflow.
382 (long long)-ULLVal > 0)
389 bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
390 StringRef Str = *this;
392 // Autosense radix if not specified.
394 Radix = GetAutoSenseRadix(Str);
396 assert(Radix > 1 && Radix <= 36);
398 // Empty strings (after the radix autosense) are invalid.
399 if (Str.empty()) return true;
401 // Skip leading zeroes. This can be a significant improvement if
402 // it means we don't need > 64 bits.
403 while (!Str.empty() && Str.front() == '0')
406 // If it was nothing but zeroes....
408 Result = APInt(64, 0);
412 // (Over-)estimate the required number of bits.
413 unsigned Log2Radix = 0;
414 while ((1U << Log2Radix) < Radix) Log2Radix++;
415 bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
417 unsigned BitWidth = Log2Radix * Str.size();
418 if (BitWidth < Result.getBitWidth())
419 BitWidth = Result.getBitWidth(); // don't shrink the result
420 else if (BitWidth > Result.getBitWidth())
421 Result = Result.zext(BitWidth);
423 APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix
424 if (!IsPowerOf2Radix) {
425 // These must have the same bit-width as Result.
426 RadixAP = APInt(BitWidth, Radix);
427 CharAP = APInt(BitWidth, 0);
430 // Parse all the bytes of the string given this radix.
432 while (!Str.empty()) {
434 if (Str[0] >= '0' && Str[0] <= '9')
435 CharVal = Str[0]-'0';
436 else if (Str[0] >= 'a' && Str[0] <= 'z')
437 CharVal = Str[0]-'a'+10;
438 else if (Str[0] >= 'A' && Str[0] <= 'Z')
439 CharVal = Str[0]-'A'+10;
443 // If the parsed value is larger than the integer radix, the string is
445 if (CharVal >= Radix)
448 // Add in this character.
449 if (IsPowerOf2Radix) {
450 Result <<= Log2Radix;
465 // Implementation of StringRef hashing.
466 hash_code llvm::hash_value(StringRef S) {
467 return hash_combine_range(S.begin(), S.end());