ValueTraits.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2020-2022, Idan Horowitz <idan.horowitz@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #pragma once
  9. #include <LibJS/Runtime/PrimitiveString.h>
  10. #include <LibJS/Runtime/Value.h>
  11. namespace JS {
  12. struct ValueTraits : public Traits<Value> {
  13. static unsigned hash(Value value)
  14. {
  15. VERIFY(!value.is_empty());
  16. if (value.is_string())
  17. return value.as_string().string().hash();
  18. if (value.is_bigint())
  19. return value.as_bigint().big_integer().hash();
  20. if (value.is_negative_zero())
  21. value = Value(0);
  22. // In the IEEE 754 standard a NaN value is encoded as any value from 0x7ff0000000000001 to 0x7fffffffffffffff,
  23. // with the least significant bits (referred to as the 'payload') carrying some kind of diagnostic information
  24. // indicating the source of the NaN. Since ECMA262 does not differentiate between different kinds of NaN values,
  25. // Sets and Maps must not differentiate between them either.
  26. // This is achieved by replacing any NaN value by a canonical qNaN.
  27. else if (value.is_nan())
  28. value = js_nan();
  29. return u64_hash(value.encoded()); // FIXME: Is this the best way to hash pointers, doubles & ints?
  30. }
  31. static bool equals(const Value a, const Value b)
  32. {
  33. return same_value_zero(a, b);
  34. }
  35. };
  36. }