From 8bd43f2cb94371899af067e73c2abf75a2425393 Mon Sep 17 00:00:00 2001 From: Shannon Booth Date: Sun, 6 Jul 2025 20:42:40 +1200 Subject: [PATCH] AK: Add hash traits for Optional 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. --- AK/Optional.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/AK/Optional.h b/AK/Optional.h index fe00c10b52..1100d2ba97 100644 --- a/AK/Optional.h +++ b/AK/Optional.h @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -656,6 +657,18 @@ ALWAYS_INLINE constexpr bool operator==(Optional const& first, OptionalNone) return !first.has_value(); } +template +struct Traits> : public DefaultTraits> { + static unsigned hash(Optional 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::hash(optional.value()); + } +}; + } #if USING_AK_GLOBALLY