Thu, 22 Jan 2015 13:21:57 +0100
Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6
michael@0 | 1 | // |
michael@0 | 2 | // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. |
michael@0 | 3 | // Use of this source code is governed by a BSD-style license that can be |
michael@0 | 4 | // found in the LICENSE file. |
michael@0 | 5 | // |
michael@0 | 6 | |
michael@0 | 7 | // numeric_lex.h: Functions to extract numeric values from string. |
michael@0 | 8 | |
michael@0 | 9 | #ifndef COMPILER_PREPROCESSOR_NUMERIC_LEX_H_ |
michael@0 | 10 | #define COMPILER_PREPROCESSOR_NUMERIC_LEX_H_ |
michael@0 | 11 | |
michael@0 | 12 | #include <sstream> |
michael@0 | 13 | |
michael@0 | 14 | namespace pp { |
michael@0 | 15 | |
michael@0 | 16 | inline std::ios::fmtflags numeric_base_int(const std::string& str) |
michael@0 | 17 | { |
michael@0 | 18 | if ((str.size() >= 2) && |
michael@0 | 19 | (str[0] == '0') && |
michael@0 | 20 | (str[1] == 'x' || str[1] == 'X')) |
michael@0 | 21 | { |
michael@0 | 22 | return std::ios::hex; |
michael@0 | 23 | } |
michael@0 | 24 | else if ((str.size() >= 1) && (str[0] == '0')) |
michael@0 | 25 | { |
michael@0 | 26 | return std::ios::oct; |
michael@0 | 27 | } |
michael@0 | 28 | return std::ios::dec; |
michael@0 | 29 | } |
michael@0 | 30 | |
michael@0 | 31 | // The following functions parse the given string to extract a numerical |
michael@0 | 32 | // value of the given type. These functions assume that the string is |
michael@0 | 33 | // of the correct form. They can only fail if the parsed value is too big, |
michael@0 | 34 | // in which case false is returned. |
michael@0 | 35 | |
michael@0 | 36 | template<typename IntType> |
michael@0 | 37 | bool numeric_lex_int(const std::string& str, IntType* value) |
michael@0 | 38 | { |
michael@0 | 39 | std::istringstream stream(str); |
michael@0 | 40 | // This should not be necessary, but MSVS has a buggy implementation. |
michael@0 | 41 | // It returns incorrect results if the base is not specified. |
michael@0 | 42 | stream.setf(numeric_base_int(str), std::ios::basefield); |
michael@0 | 43 | |
michael@0 | 44 | stream >> (*value); |
michael@0 | 45 | return !stream.fail(); |
michael@0 | 46 | } |
michael@0 | 47 | |
michael@0 | 48 | template<typename FloatType> |
michael@0 | 49 | bool numeric_lex_float(const std::string& str, FloatType* value) |
michael@0 | 50 | { |
michael@0 | 51 | std::istringstream stream(str); |
michael@0 | 52 | // Force "C" locale so that decimal character is always '.', and |
michael@0 | 53 | // not dependent on the current locale. |
michael@0 | 54 | stream.imbue(std::locale::classic()); |
michael@0 | 55 | |
michael@0 | 56 | stream >> (*value); |
michael@0 | 57 | return !stream.fail(); |
michael@0 | 58 | } |
michael@0 | 59 | |
michael@0 | 60 | } // namespace pp. |
michael@0 | 61 | #endif // COMPILER_PREPROCESSOR_NUMERIC_LEX_H_ |