parse_string.h
2.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include <locale>
#include <sstream>
#include <type_traits>
#include "core/common/common.h"
namespace onnxruntime {
/**
* Tries to parse a value from an entire string.
*/
template <typename T>
bool TryParseStringWithClassicLocale(const std::string& str, T& value) {
if (std::is_integral<T>::value && std::is_unsigned<T>::value) {
// if T is unsigned integral type, reject negative values which will wrap
if (!str.empty() && str[0] == '-') {
return false;
}
}
// don't allow leading whitespace
if (!str.empty() && std::isspace(str[0], std::locale::classic())) {
return false;
}
std::istringstream is{str};
is.imbue(std::locale::classic());
T parsed_value{};
const bool parse_successful =
is >> parsed_value &&
is.get() == std::istringstream::traits_type::eof(); // don't allow trailing characters
if (!parse_successful) {
return false;
}
value = std::move(parsed_value);
return true;
}
inline bool TryParseStringWithClassicLocale(const std::string& str, std::string& value) {
value = str;
return true;
}
inline bool TryParseStringWithClassicLocale(const std::string& str, bool& value) {
if (str == "0" || str == "False" || str == "false") {
value = false;
return true;
}
if (str == "1" || str == "True" || str == "true") {
value = true;
return true;
}
return false;
}
/**
* Parses a value from an entire string.
*/
template <typename T>
Status ParseStringWithClassicLocale(const std::string& s, T& value) {
ORT_RETURN_IF_NOT(TryParseStringWithClassicLocale(s, value), "Failed to parse value: \"", value, "\"");
return Status::OK();
}
/**
* Parses a value from an entire string.
*/
template <typename T>
T ParseStringWithClassicLocale(const std::string& s) {
T value{};
ORT_THROW_IF_ERROR(ParseStringWithClassicLocale(s, value));
return value;
}
} // namespace onnxruntime