aboutsummaryrefslogtreecommitdiffstats
path: root/host/lib/utils/cast.cpp
blob: 6b008ff4503c3bff1f84e75fd48b6e20a5614555 (plain)
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
//
// Copyright 2019 Ettus Research, a National Instruments Brand
//
// SPDX-License-Identifier: GPL-3.0-or-later
//

#include <uhd/utils/cast.hpp>
#include <uhd/exception.hpp>
#include <boost/algorithm/string.hpp>

using namespace uhd;

template <>
bool cast::from_str(const std::string& val)
{
    try {
        return (std::stoi(val) != 0);
    } catch (std::exception& ex) {
        if (boost::algorithm::to_lower_copy(val) == "true"
                   || boost::algorithm::to_lower_copy(val) == "yes"
                   || boost::algorithm::to_lower_copy(val) == "y"
                   || val == "1") {
            return true;
        } else if (boost::algorithm::to_lower_copy(val) == "false"
                   || boost::algorithm::to_lower_copy(val) == "no"
                   || boost::algorithm::to_lower_copy(val) == "n"
                   || val == "0") {
            return false;
        } else {
            throw uhd::runtime_error("Cannot convert `" + val + "' to boolean!");
            return false;
        }
    }
}

template <>
double cast::from_str(const std::string& val)
{
    try {
        return std::stod(val);
    } catch (std::invalid_argument&) {
        throw uhd::runtime_error(std::string("Cannot convert `") + val + "' to double!");
    } catch (std::out_of_range&) {
        throw uhd::runtime_error(std::string("Cannot convert `") + val + "' to double!");
    }
}

template <>
int cast::from_str(const std::string& val)
{
    try {
        return std::stoi(val);
    } catch (std::invalid_argument&) {
        throw uhd::runtime_error(std::string("Cannot convert `") + val + "' to int!");
    } catch (std::out_of_range&) {
        throw uhd::runtime_error(std::string("Cannot convert `") + val + "' to int!");
    }
}

template <>
std::string cast::from_str(const std::string& val)
{
    return val;
}