| 1 | // |
| 2 | // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. |
| 3 | // Use of this source code is governed by a BSD-style license that can be |
| 4 | // found in the LICENSE file. |
| 5 | // |
| 6 | |
| 7 | // numeric_lex.h: Functions to extract numeric values from string. |
| 8 | |
| 9 | #ifndef COMPILER_PREPROCESSOR_NUMERICLEX_H_ |
| 10 | #define COMPILER_PREPROCESSOR_NUMERICLEX_H_ |
| 11 | |
| 12 | #include <sstream> |
| 13 | |
| 14 | namespace angle |
| 15 | { |
| 16 | |
| 17 | namespace pp |
| 18 | { |
| 19 | |
| 20 | inline std::ios::fmtflags numeric_base_int(const std::string &str) |
| 21 | { |
| 22 | if ((str.size() >= 2) && (str[0] == '0') && (str[1] == 'x' || str[1] == 'X')) |
| 23 | { |
| 24 | return std::ios::hex; |
| 25 | } |
| 26 | if ((str.size() >= 1) && (str[0] == '0')) |
| 27 | { |
| 28 | return std::ios::oct; |
| 29 | } |
| 30 | return std::ios::dec; |
| 31 | } |
| 32 | |
| 33 | // The following functions parse the given string to extract a numerical |
| 34 | // value of the given type. These functions assume that the string is |
| 35 | // of the correct form. They can only fail if the parsed value is too big, |
| 36 | // in which case false is returned. |
| 37 | |
| 38 | template <typename IntType> |
| 39 | bool numeric_lex_int(const std::string &str, IntType *value) |
| 40 | { |
| 41 | std::istringstream stream(str); |
| 42 | // This should not be necessary, but MSVS has a buggy implementation. |
| 43 | // It returns incorrect results if the base is not specified. |
| 44 | stream.setf(numeric_base_int(str), std::ios::basefield); |
| 45 | |
| 46 | stream >> (*value); |
| 47 | return !stream.fail(); |
| 48 | } |
| 49 | |
| 50 | } // namespace pp |
| 51 | |
| 52 | } // namespace angle |
| 53 | |
| 54 | #endif // COMPILER_PREPROCESSOR_NUMERICLEX_H_ |
| 55 | |