blob: ec375a4ec50131c727e24587afd7c36366a4e0c7 [file] [log] [blame]
daniel@transgaming.com91ed1492010-10-29 03:11:43 +00001//
2// Copyright (c) 2010 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#include <math.h>
8#include <stdlib.h>
9
Zhenyao Mof1d723c2013-09-23 14:57:07 -040010#include <cerrno>
11#include <limits>
12
daniel@transgaming.com91ed1492010-10-29 03:11:43 +000013#include "util.h"
14
15#ifdef _MSC_VER
16 #include <locale.h>
17#else
18 #include <sstream>
19#endif
20
Zhenyao Mof1d723c2013-09-23 14:57:07 -040021bool atof_clamp(const char *str, float *value)
daniel@transgaming.com91ed1492010-10-29 03:11:43 +000022{
Zhenyao Mof1d723c2013-09-23 14:57:07 -040023 bool success = true;
daniel@transgaming.com91ed1492010-10-29 03:11:43 +000024#ifdef _MSC_VER
daniel@transgaming.com9a76b812010-12-12 08:53:34 +000025 _locale_t l = _create_locale(LC_NUMERIC, "C");
Zhenyao Mof1d723c2013-09-23 14:57:07 -040026 double dvalue = _atof_l(str, l);
daniel@transgaming.com9a76b812010-12-12 08:53:34 +000027 _free_locale(l);
Zhenyao Mof1d723c2013-09-23 14:57:07 -040028 if (errno == ERANGE || dvalue > std::numeric_limits<float>::max())
29 success = false;
30 else
31 *value = static_cast<float>(dvalue);
daniel@transgaming.com91ed1492010-10-29 03:11:43 +000032#else
daniel@transgaming.com91ed1492010-10-29 03:11:43 +000033 std::istringstream s(str);
34 std::locale l("C");
35 s.imbue(l);
Zhenyao Mof1d723c2013-09-23 14:57:07 -040036 s >> *value;
37 if (s.fail())
38 success = false;
daniel@transgaming.com91ed1492010-10-29 03:11:43 +000039#endif
Zhenyao Mof1d723c2013-09-23 14:57:07 -040040 if (!success)
41 *value = std::numeric_limits<float>::max();
42 return success;
daniel@transgaming.com91ed1492010-10-29 03:11:43 +000043}
Zhenyao Mof1d723c2013-09-23 14:57:07 -040044
45bool atoi_clamp(const char *str, int *value)
46{
47 long int lvalue = strtol(str, 0, 0);
48 if (errno == ERANGE || lvalue > std::numeric_limits<int>::max())
49 {
50 *value = std::numeric_limits<int>::max();
51 return false;
52 }
53 *value = static_cast<int>(lvalue);
54 return true;
55}
56