From c452b865715c9eb95205c113f0b1c4957446863e Mon Sep 17 00:00:00 2001 From: Ze Gan <ganze718@gmail.com> Date: Mon, 28 Dec 2020 14:01:19 +0800 Subject: [PATCH] polish code Signed-off-by: Ze Gan <ganze718@gmail.com> --- common/boolean.h | 22 ++++++++-------------- tests/boolean_ut.cpp | 27 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 14 deletions(-) diff --git a/common/boolean.h b/common/boolean.h index ba46be4ce..12219f51b 100644 --- a/common/boolean.h +++ b/common/boolean.h @@ -16,6 +16,10 @@ class Boolean { return m_boolean; } + operator bool&() + { + return m_boolean; + } protected: bool m_boolean; }; @@ -31,32 +35,22 @@ class AlphaBoolean : public Boolean static inline std::ostream &operator<<(std::ostream &out, const AlphaBoolean &b) { - bool value = b; - out << std::boolalpha << value; - return out; + return out << std::boolalpha << (bool)(b); } static inline std::istream &operator>>(std::istream &in, AlphaBoolean &b) { - bool value = false; - in >> std::boolalpha >> value; - b = value; - return in; + return in >> std::boolalpha >> (bool &)(b); } static inline std::ostream &operator<<(std::ostream &out, const Boolean &b) { - bool value = b; - out << value; - return out; + return out << (bool)(b); } static inline std::istream &operator>>(std::istream &in, Boolean &b) { - bool value = false; - in >> value; - b = value; - return in; + return in >> (bool &)(b); } } diff --git a/tests/boolean_ut.cpp b/tests/boolean_ut.cpp index fc0aa784a..c8a214ada 100644 --- a/tests/boolean_ut.cpp +++ b/tests/boolean_ut.cpp @@ -4,6 +4,33 @@ #include <sstream> +TEST(BOOLEAN, boolean) +{ + swss::Boolean b; + + b = true; + std::ostringstream ost; + ost << b; + EXPECT_EQ(ost.str(), "1"); + + b = false; + std::ostringstream osf; + osf << b; + EXPECT_EQ(osf.str(), "0"); + + b = false; + std::istringstream ist("1"); + ist >> b; + EXPECT_TRUE(b); + EXPECT_FALSE(ist.fail()); + + b = true; + std::istringstream isf("0"); + isf >> b; + EXPECT_FALSE(b); + EXPECT_FALSE(isf.fail()); +} + TEST(BOOLEAN, alpha_boolean) { swss::AlphaBoolean bt(true);