Skip to content
This repository was archived by the owner on Aug 5, 2022. It is now read-only.

Commit a26f0ad

Browse files
committed
convertTo: Allow hexadecimal boolean
convertTo<bool> now allow 0x0 and 0x1 as input. It was inconsistant with the other types. Do that by converting the string to uint8_t and then testing for 0 or 1. Also do a case insensitive comparison for "true" and "false". Signed-off-by: Kevin Rocard <[email protected]>
1 parent 50bace1 commit a26f0ad

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

utility/convert.hpp

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,10 @@
3333
#include <limits>
3434
#include <sstream>
3535
#include <string>
36+
#include <algorithm>
3637
#include <stdint.h>
3738
#include <cmath>
39+
#include <cctype>
3840
#include <type_traits>
3941

4042
/* details namespace is here to hide implementation details to header end user. It
@@ -184,6 +186,8 @@ static inline bool convertToVia(const std::string &str, T &result)
184186
* @param[out] result reference to object where to store the result.
185187
*
186188
* @return true if conversion was successful, false otherwise.
189+
*
190+
* @FIXME: Unit tests were not imported with this conversion library.
187191
*/
188192
template <typename T>
189193
static inline bool convertTo(const std::string &str, T &result)
@@ -302,12 +306,30 @@ inline bool convertTo<double>(const std::string &str, double &result)
302306
template <>
303307
inline bool convertTo<bool>(const std::string &str, bool &result)
304308
{
305-
if (str == "0" || str == "FALSE" || str == "false") {
309+
// Try the numerical representation
310+
uint8_t numeric;
311+
if (convertTo(str, numeric)) {
312+
switch (numeric) {
313+
case 0:
314+
result = false;
315+
return true;
316+
case 1:
317+
result = true;
318+
return true;
319+
default:
320+
return false;
321+
}
322+
}
323+
324+
std::string lower = str;
325+
transform(begin(str), end(str), begin(lower), tolower);
326+
327+
if (lower == "false") {
306328
result = false;
307329
return true;
308330
}
309331

310-
if (str == "1" || str == "TRUE" || str == "true") {
332+
if (lower == "true") {
311333
result = true;
312334
return true;
313335
}

0 commit comments

Comments
 (0)