HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
parse_string.h
Go to the documentation of this file.
1 // Copyright (c) Microsoft Corporation. All rights reserved.
2 // Licensed under the MIT License.
3 
4 #pragma once
5 
6 #include <locale>
7 #include <sstream>
8 #include <string_view>
9 #include <type_traits>
10 
11 #include "core/common/common.h"
12 
13 namespace onnxruntime {
14 
15 /**
16  * Tries to parse a value from an entire string.
17  */
18 template <typename T>
21  // if T is unsigned integral type, reject negative values which will wrap
22  if (!str.empty() && str[0] == '-') {
23  return false;
24  }
25  }
26 
27  // don't allow leading whitespace
28  if (!str.empty() && std::isspace(str[0], std::locale::classic())) {
29  return false;
30  }
31 
32  std::istringstream is{std::string{str}};
33  is.imbue(std::locale::classic());
34  T parsed_value{};
35 
36  const bool parse_successful =
37  is >> parsed_value &&
38  is.get() == std::istringstream::traits_type::eof(); // don't allow trailing characters
39  if (!parse_successful) {
40  return false;
41  }
42 
43  value = std::move(parsed_value);
44  return true;
45 }
46 
48  value = str;
49  return true;
50 }
51 
53  if (str == "0" || str == "False" || str == "false") {
54  value = false;
55  return true;
56  }
57 
58  if (str == "1" || str == "True" || str == "true") {
59  value = true;
60  return true;
61  }
62 
63  return false;
64 }
65 
66 /**
67  * Parses a value from an entire string.
68  */
69 template <typename T>
71  ORT_RETURN_IF_NOT(TryParseStringWithClassicLocale(s, value), "Failed to parse value: \"", value, "\"");
72  return Status::OK();
73 }
74 
75 /**
76  * Parses a value from an entire string.
77  */
78 template <typename T>
80  T value{};
82  return value;
83 }
84 
85 } // namespace onnxruntime
bool TryParseStringWithClassicLocale(std::string_view str, T &value)
Definition: parse_string.h:19
GLsizei const GLchar *const * string
Definition: glcorearb.h:814
GLsizei const GLfloat * value
Definition: glcorearb.h:824
GLdouble s
Definition: glad.h:3009
basic_string_view< char > string_view
Definition: core.h:522
bool isspace(char c)
Definition: strutil.h:799
#define ORT_RETURN_IF_NOT(condition,...)
Definition: common.h:202
Status ParseStringWithClassicLocale(std::string_view s, T &value)
Definition: parse_string.h:70
Definition: core.h:1131
#define ORT_THROW_IF_ERROR(expr)
Definition: common.h:236