bool str_to_bool(StringPiece* src) { auto b = src->begin(), e = src->end(); for (;; ++b) { FOLLY_RANGE_CHECK_STRINGPIECE( b < e, "No non-whitespace characters found in input string", *src); if (!isspace(*b)) break; } bool result; size_t len = e - b; switch (*b) { case '0': case '1': { result = false; for (; b < e && isdigit(*b); ++b) { FOLLY_RANGE_CHECK_STRINGPIECE( !result && (*b == '0' || *b == '1'), "Integer overflow when parsing bool: must be 0 or 1", *src); result = (*b == '1'); } break; } case 'y': case 'Y': result = true; if (!bool_str_cmp(&b, len, "yes")) { ++b; // accept the single 'y' character } break; case 'n': case 'N': result = false; if (!bool_str_cmp(&b, len, "no")) { ++b; } break; case 't': case 'T': result = true; if (!bool_str_cmp(&b, len, "true")) { ++b; } break; case 'f': case 'F': result = false; if (!bool_str_cmp(&b, len, "false")) { ++b; } break; case 'o': case 'O': if (bool_str_cmp(&b, len, "on")) { result = true; } else if (bool_str_cmp(&b, len, "off")) { result = false; } else { FOLLY_RANGE_CHECK_STRINGPIECE(false, "Invalid value for bool", *src); } break; default: FOLLY_RANGE_CHECK_STRINGPIECE(false, "Invalid value for bool", *src); } src->assign(b, e); return result; }
bool str_to_bool(StringPiece* src) { auto b = src->begin(), e = src->end(); for (;; ++b) { FOLLY_RANGE_CHECK(b < e, "No non-whitespace characters found in input string"); if (!isspace(*b)) break; } bool result; size_t len = e - b; switch (*b) { case '0': case '1': { // Attempt to parse the value as an integer StringPiece tmp(*src); uint8_t value = to<uint8_t>(&tmp); // Only accept 0 or 1 FOLLY_RANGE_CHECK(value <= 1, "Integer overflow when parsing bool: must be 0 or 1"); b = tmp.begin(); result = (value == 1); break; } case 'y': case 'Y': result = true; if (!bool_str_cmp(&b, len, "yes")) { ++b; // accept the single 'y' character } break; case 'n': case 'N': result = false; if (!bool_str_cmp(&b, len, "no")) { ++b; } break; case 't': case 'T': result = true; if (!bool_str_cmp(&b, len, "true")) { ++b; } break; case 'f': case 'F': result = false; if (!bool_str_cmp(&b, len, "false")) { ++b; } break; case 'o': case 'O': if (bool_str_cmp(&b, len, "on")) { result = true; } else if (bool_str_cmp(&b, len, "off")) { result = false; } else { FOLLY_RANGE_CHECK(false, "Invalid value for bool"); } break; default: FOLLY_RANGE_CHECK(false, "Invalid value for bool"); } src->assign(b, e); return result; }