LibJS: Enable storing Value and Handle<Value> in HashMaps

We have the right conversions to make this work, so let's make it
possible to have a `HashMap<JS::Handle<T>, V>` and look for a specific
T inside it without having to create a temporary handle.

This involves adding some operator== implementations, and some
specializations of AK::Traits.
This commit is contained in:
Andrew Kaster 2023-08-21 15:13:18 -06:00 committed by Andreas Kling
parent 685ef4ec82
commit 96600e77c2
Notes: sideshowbarker 2024-07-16 23:44:30 +09:00
2 changed files with 42 additions and 0 deletions

View File

@ -162,6 +162,9 @@ public:
auto value() const { return *m_value; }
bool is_null() const { return m_handle.is_null() && !m_value.has_value(); }
bool operator==(Value const& value) const { return value == m_value; }
bool operator==(Handle<Value> const& other) const { return other.m_value == this->m_value; }
private:
explicit Handle(Value value)
: m_value(value)
@ -184,3 +187,25 @@ inline Handle<Value> make_handle(Value value)
}
}
namespace AK {
template<typename T>
struct Traits<JS::Handle<T>> : public GenericTraits<JS::Handle<T>> {
static unsigned hash(JS::Handle<T> const& handle) { return Traits<T>::hash(handle); }
};
template<>
struct Traits<JS::Handle<JS::Value>> : public GenericTraits<JS::Handle<JS::Value>> {
static unsigned hash(JS::Handle<JS::Value> const& handle) { return Traits<JS::Value>::hash(handle.value()); }
};
namespace Detail {
template<typename T>
inline constexpr bool IsHashCompatible<JS::Handle<T>, T> = true;
template<typename T>
inline constexpr bool IsHashCompatible<T, JS::Handle<T>> = true;
}
}

View File

@ -619,6 +619,18 @@ public:
return *this;
}
template<typename O>
ALWAYS_INLINE bool operator==(Optional<O> const& other) const
{
return has_value() == other.has_value() && (!has_value() || value() == other.value());
}
template<typename O>
ALWAYS_INLINE bool operator==(O const& other) const
{
return has_value() && value() == other;
}
void clear()
{
m_value = {};
@ -688,4 +700,9 @@ struct Formatter<JS::Value> : Formatter<StringView> {
}
};
template<>
struct Traits<JS::Value> : GenericTraits<JS::Value> {
static unsigned hash(JS::Value value) { return Traits<u64>::hash(value.encoded()); }
};
}