AK: Add hash traits for Optional<T>

To enable storing it in a hashmap. 13 is a somewhat arbitrary
value, something like 0 is not appropriate since a lot of types
return 0 as a hash for an invalid / empty state.
This commit is contained in:
Shannon Booth 2025-07-06 20:42:40 +12:00 committed by Tim Ledbetter
parent 8ca956e6f1
commit 8bd43f2cb9

View File

@ -10,6 +10,7 @@
#include <AK/Assertions.h>
#include <AK/Noncopyable.h>
#include <AK/StdLibExtras.h>
#include <AK/Traits.h>
#include <AK/Try.h>
#include <AK/Types.h>
#include <AK/kmalloc.h>
@ -656,6 +657,18 @@ ALWAYS_INLINE constexpr bool operator==(Optional<T> const& first, OptionalNone)
return !first.has_value();
}
template<typename T>
struct Traits<Optional<T>> : public DefaultTraits<Optional<T>> {
static unsigned hash(Optional<T> const& optional)
{
// Arbitrary-ish value for an empty optional, but not 0 as that is a common 'hash' for many T's.
if (!optional.has_value())
return 13;
return Traits<T>::hash(optional.value());
}
};
}
#if USING_AK_GLOBALLY