1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // numeric_lex.h: Functions to extract numeric values from string. 16 17 #ifndef COMPILER_PREPROCESSOR_NUMERIC_LEX_H_ 18 #define COMPILER_PREPROCESSOR_NUMERIC_LEX_H_ 19 20 #include <sstream> 21 22 namespace pp { 23 24 inline std::ios::fmtflags numeric_base_int(const std::string& str) 25 { 26 if ((str.size() >= 2) && 27 (str[0] == '0') && 28 (str[1] == 'x' || str[1] == 'X')) 29 { 30 return std::ios::hex; 31 } 32 else if ((str.size() >= 1) && (str[0] == '0')) 33 { 34 return std::ios::oct; 35 } 36 return std::ios::dec; 37 } 38 39 // The following functions parse the given string to extract a numerical 40 // value of the given type. These functions assume that the string is 41 // of the correct form. They can only fail if the parsed value is too big, 42 // in which case false is returned. 43 44 template<typename IntType> 45 bool numeric_lex_int(const std::string& str, IntType* value) 46 { 47 std::istringstream stream(str); 48 // This should not be necessary, but MSVS has a buggy implementation. 49 // It returns incorrect results if the base is not specified. 50 stream.setf(numeric_base_int(str), std::ios::basefield); 51 52 stream >> (*value); 53 return !stream.fail(); 54 } 55 56 template<typename FloatType> 57 bool numeric_lex_float(const std::string& str, FloatType* value) 58 { 59 std::istringstream stream(str); 60 // Force "C" locale so that decimal character is always '.', and 61 // not dependent on the current locale. 62 stream.imbue(std::locale::classic()); 63 64 stream >> (*value); 65 return !stream.fail(); 66 } 67 68 } // namespace pp. 69 #endif // COMPILER_PREPROCESSOR_NUMERIC_LEX_H_ 70