From b12c3b203773649e61f61344829924ab7ad43110 Mon Sep 17 00:00:00 2001 From: Aaron Rossetto Date: Wed, 18 Mar 2020 07:31:16 -0500 Subject: utils: Add bool specialization to cast::from_str() This adds a specialization to `uhd::cast::from_str()` to handle `bool` as a target type and interpret strings like 'y', 'Y', 'n', 'No', 'True', 'False', etc. as Boolean values, as well as the traditional '0' and '1' (which also work). --- host/lib/utils/cast.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'host/lib/utils') diff --git a/host/lib/utils/cast.cpp b/host/lib/utils/cast.cpp index 635d844ee..6b008ff45 100644 --- a/host/lib/utils/cast.cpp +++ b/host/lib/utils/cast.cpp @@ -5,9 +5,34 @@ // #include +#include +#include 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) { -- cgit v1.2.3