From e13c96157cb87c70471178f27a4e1c6f4336d073 Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Fri, 11 Feb 2022 09:43:02 -0500 Subject: [PATCH] LibSQL: Implement converting float and tuple values to a boolean --- Tests/LibSQL/TestSqlValueAndTuple.cpp | 13 ++++++++++++- Userland/Libraries/LibSQL/Value.cpp | 18 ++++++++++++++++++ Userland/Libraries/LibSQL/ValueImpl.h | 3 ++- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/Tests/LibSQL/TestSqlValueAndTuple.cpp b/Tests/LibSQL/TestSqlValueAndTuple.cpp index 23e6f2f0fc..df34af70bb 100644 --- a/Tests/LibSQL/TestSqlValueAndTuple.cpp +++ b/Tests/LibSQL/TestSqlValueAndTuple.cpp @@ -169,7 +169,18 @@ TEST_CASE(float_value) EXPECT(v.to_int().has_value()); EXPECT_EQ(v.to_int().value(), 3); EXPECT_EQ(v.to_string(), "3.14"); - EXPECT(!v.to_bool().has_value()); + EXPECT(v.to_bool().has_value()); + EXPECT(v.to_bool().value()); + + v = 0.0; + EXPECT(!v.is_null()); + EXPECT(v.to_double().has_value()); + EXPECT(v.to_double().value() < NumericLimits().epsilon()); + EXPECT(v.to_int().has_value()); + EXPECT_EQ(v.to_int().value(), 0); + EXPECT_EQ(v.to_string(), "0"); + EXPECT(v.to_bool().has_value()); + EXPECT(!v.to_bool().value()); } { SQL::Value v(3.14); diff --git a/Userland/Libraries/LibSQL/Value.cpp b/Userland/Libraries/LibSQL/Value.cpp index 0e1146e10e..d912c4fbd6 100644 --- a/Userland/Libraries/LibSQL/Value.cpp +++ b/Userland/Libraries/LibSQL/Value.cpp @@ -728,6 +728,11 @@ Optional FloatImpl::to_int() const return static_cast(round(value())); } +Optional FloatImpl::to_bool() const +{ + return fabs(value()) > NumericLimits::epsilon(); +} + Optional FloatImpl::to_double() const { return value(); @@ -999,6 +1004,19 @@ int TupleImpl::compare(Value const& other) const return 0; } +Optional TupleImpl::to_bool() const +{ + for (auto const& value : value()) { + auto as_bool = Value(value).to_bool(); + if (!as_bool.has_value()) + return {}; + if (!as_bool.value()) + return false; + } + + return true; +} + void TupleImpl::serialize(Serializer& serializer) const { serializer.serialize(*m_descriptor); diff --git a/Userland/Libraries/LibSQL/ValueImpl.h b/Userland/Libraries/LibSQL/ValueImpl.h index 70fe611ed5..477e783a51 100644 --- a/Userland/Libraries/LibSQL/ValueImpl.h +++ b/Userland/Libraries/LibSQL/ValueImpl.h @@ -159,7 +159,7 @@ public: [[nodiscard]] String to_string() const; [[nodiscard]] Optional to_int() const; [[nodiscard]] Optional to_double() const; - [[nodiscard]] static Optional to_bool() { return {}; } + [[nodiscard]] Optional to_bool() const; [[nodiscard]] static bool to_vector(Vector&) { return false; } void assign(Value const&); void assign_string(String const&); @@ -250,6 +250,7 @@ public: [[nodiscard]] size_t length() const; [[nodiscard]] bool can_cast(Value const&) const; [[nodiscard]] int compare(Value const& other) const; + [[nodiscard]] Optional to_bool() const; virtual bool validate_before_assignment(Vector const&) override; virtual bool validate(BaseTypeImpl const&) override;