Skip to content

Commit

Permalink
LibSQL: Implement converting float and tuple values to a boolean
Browse files Browse the repository at this point in the history
  • Loading branch information
trflynn89 authored and linusg committed Feb 13, 2022
1 parent 8fab99e commit e13c961
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
13 changes: 12 additions & 1 deletion Tests/LibSQL/TestSqlValueAndTuple.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<double>().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);
Expand Down
18 changes: 18 additions & 0 deletions Userland/Libraries/LibSQL/Value.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,11 @@ Optional<int> FloatImpl::to_int() const
return static_cast<int>(round(value()));
}

Optional<bool> FloatImpl::to_bool() const
{
return fabs(value()) > NumericLimits<double>::epsilon();
}

Optional<double> FloatImpl::to_double() const
{
return value();
Expand Down Expand Up @@ -999,6 +1004,19 @@ int TupleImpl::compare(Value const& other) const
return 0;
}

Optional<bool> 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<TupleDescriptor>(*m_descriptor);
Expand Down
3 changes: 2 additions & 1 deletion Userland/Libraries/LibSQL/ValueImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ class FloatImpl : public Impl<double> {
[[nodiscard]] String to_string() const;
[[nodiscard]] Optional<int> to_int() const;
[[nodiscard]] Optional<double> to_double() const;
[[nodiscard]] static Optional<bool> to_bool() { return {}; }
[[nodiscard]] Optional<bool> to_bool() const;
[[nodiscard]] static bool to_vector(Vector<Value>&) { return false; }
void assign(Value const&);
void assign_string(String const&);
Expand Down Expand Up @@ -250,6 +250,7 @@ class TupleImpl : public ContainerValueImpl {
[[nodiscard]] size_t length() const;
[[nodiscard]] bool can_cast(Value const&) const;
[[nodiscard]] int compare(Value const& other) const;
[[nodiscard]] Optional<bool> to_bool() const;

virtual bool validate_before_assignment(Vector<Value> const&) override;
virtual bool validate(BaseTypeImpl const&) override;
Expand Down

0 comments on commit e13c961

Please sign in to comment.