Imported Upstream version 1.25.0
[platform/core/ml/nnfw.git] / compiler / souschef / src / LexicalCast.cpp
1 /*
2  * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *    http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "souschef/LexicalCast.h"
18
19 #include <cassert>
20 #include <limits>
21 #include <stdexcept>
22
23 namespace souschef
24 {
25
26 template <> float to_number(const std::string &s) { return std::stof(s); }
27 template <> int to_number(const std::string &s) { return std::stoi(s); }
28 template <> int16_t to_number(const std::string &s)
29 {
30   // There are no standard function to parse int16_t or short int
31   // This function simulates behavior similar stoi, stol and stoll
32   int res = std::stol(s);
33   // standard does not specify string in error message, this is arbitrary
34   if (res < std::numeric_limits<int16_t>::min() || res > std::numeric_limits<int16_t>::max())
35   {
36     throw std::out_of_range("to_number<int16_t>");
37   }
38   return res;
39 }
40 template <> int64_t to_number(const std::string &s) { return std::stoll(s); }
41 template <> uint8_t to_number(const std::string &s)
42 {
43   int temp = std::stoi(s);
44   assert(temp >= 0);
45   assert(temp <= std::numeric_limits<uint8_t>::max());
46   return static_cast<uint8_t>(temp);
47 }
48 template <> int8_t to_number(const std::string &s)
49 {
50   int temp = std::stoi(s);
51   assert(temp >= std::numeric_limits<int8_t>::min());
52   assert(temp <= std::numeric_limits<int8_t>::max());
53   return static_cast<int8_t>(temp);
54 }
55 template <> bool to_number(const std::string &s)
56 {
57   if (s == "T" || s == "t" || s == "TRUE" || s == "true" || s == "1")
58     return true;
59   if (s == "F" || s == "f" || s == "FALSE" || s == "false" || s == "0")
60     return false;
61   throw std::invalid_argument("Unsupported boolean argument");
62 }
63 template <> std::string to_number(const std::string &s) { return s; }
64
65 } // namespace souschef