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"
13 const size_t StringRef::npos;
15 /// GetAsUnsignedInteger - Workhorse method that converts a integer character
16 /// sequence of radix up to 36 to an unsigned long long value.
17 static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix,
18 unsigned long long &Result) {
19 // Autosense radix if not specified.
30 } else if (Str[1] == 'b') {
40 // Empty strings (after the radix autosense) are invalid.
41 if (Str.empty()) return true;
43 // Parse all the bytes of the string given this radix. Watch for overflow.
45 while (!Str.empty()) {
47 if (Str[0] >= '0' && Str[0] <= '9')
49 else if (Str[0] >= 'a' && Str[0] <= 'z')
50 CharVal = Str[0]-'a'+10;
51 else if (Str[0] >= 'A' && Str[0] <= 'Z')
52 CharVal = Str[0]-'A'+10;
56 // If the parsed value is larger than the integer radix, the string is
61 // Add in this character.
62 unsigned long long PrevResult = Result;
63 Result = Result*Radix+CharVal;
65 // Check for overflow.
66 if (Result < PrevResult)
75 bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const {
76 return GetAsUnsignedInteger(*this, Radix, Result);
80 bool StringRef::getAsInteger(unsigned Radix, long long &Result) const {
81 unsigned long long ULLVal;
83 // Handle positive strings first.
84 if (empty() || front() != '-') {
85 if (GetAsUnsignedInteger(*this, Radix, ULLVal) ||
86 // Check for value so large it overflows a signed value.
87 (long long)ULLVal < 0)
93 // Get the positive part of the value.
94 if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) ||
95 // Reject values so large they'd overflow as negative signed, but allow
96 // "-0". This negates the unsigned so that the negative isn't undefined
97 // on signed overflow.
98 (long long)-ULLVal > 0)
105 bool StringRef::getAsInteger(unsigned Radix, int &Result) const {
107 if (getAsInteger(Radix, Val) ||
114 bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const {
115 unsigned long long Val;
116 if (getAsInteger(Radix, Val) ||
117 (unsigned)Val != Val)