michael@0: // michael@0: // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: // michael@0: michael@0: // numeric_lex.h: Functions to extract numeric values from string. michael@0: michael@0: #ifndef COMPILER_PREPROCESSOR_NUMERIC_LEX_H_ michael@0: #define COMPILER_PREPROCESSOR_NUMERIC_LEX_H_ michael@0: michael@0: #include michael@0: michael@0: namespace pp { michael@0: michael@0: inline std::ios::fmtflags numeric_base_int(const std::string& str) michael@0: { michael@0: if ((str.size() >= 2) && michael@0: (str[0] == '0') && michael@0: (str[1] == 'x' || str[1] == 'X')) michael@0: { michael@0: return std::ios::hex; michael@0: } michael@0: else if ((str.size() >= 1) && (str[0] == '0')) michael@0: { michael@0: return std::ios::oct; michael@0: } michael@0: return std::ios::dec; michael@0: } michael@0: michael@0: // The following functions parse the given string to extract a numerical michael@0: // value of the given type. These functions assume that the string is michael@0: // of the correct form. They can only fail if the parsed value is too big, michael@0: // in which case false is returned. michael@0: michael@0: template michael@0: bool numeric_lex_int(const std::string& str, IntType* value) michael@0: { michael@0: std::istringstream stream(str); michael@0: // This should not be necessary, but MSVS has a buggy implementation. michael@0: // It returns incorrect results if the base is not specified. michael@0: stream.setf(numeric_base_int(str), std::ios::basefield); michael@0: michael@0: stream >> (*value); michael@0: return !stream.fail(); michael@0: } michael@0: michael@0: template michael@0: bool numeric_lex_float(const std::string& str, FloatType* value) michael@0: { michael@0: std::istringstream stream(str); michael@0: // Force "C" locale so that decimal character is always '.', and michael@0: // not dependent on the current locale. michael@0: stream.imbue(std::locale::classic()); michael@0: michael@0: stream >> (*value); michael@0: return !stream.fail(); michael@0: } michael@0: michael@0: } // namespace pp. michael@0: #endif // COMPILER_PREPROCESSOR_NUMERIC_LEX_H_