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#include <cmath>
22
23namespace pp {
24
25inline std::ios::fmtflags numeric_base_int(const std::string& str)
26{
27 if ((str.size() >= 2) &&
28 (str[0] == '0') &&
29 (str[1] == 'x' || str[1] == 'X'))
30 {
31 return std::ios::hex;
32 }
33 else if ((str.size() >= 1) && (str[0] == '0'))
34 {
35 return std::ios::oct;
36 }
37 return std::ios::dec;
38}
39
40// The following functions parse the given string to extract a numerical
41// value of the given type. These functions assume that the string is
42// of the correct form. They can only fail if the parsed value is too big,
43// in which case false is returned.
44
45template<typename IntType>
46bool numeric_lex_int(const std::string& str, IntType* value)
47{
48 std::istringstream stream(str);
49 // This should not be necessary, but MSVS has a buggy implementation.
50 // It returns incorrect results if the base is not specified.
51 stream.setf(numeric_base_int(str), std::ios::basefield);
52
53 stream >> (*value);
54 return !stream.fail();
55}
56
57template<typename FloatType>
58bool numeric_lex_float(const std::string& str, FloatType* value)
59{
60 std::istringstream stream(str);
61 // Force "C" locale so that decimal character is always '.', and
62 // not dependent on the current locale.
63 stream.imbue(std::locale::classic());
64
65 stream >> (*value);
66 return !stream.fail() && std::isfinite(*value);
67}
68
69} // namespace pp.
70#endif // COMPILER_PREPROCESSOR_NUMERIC_LEX_H_
71