ValueTraits.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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/BigInt.h>
  10. #include <LibJS/Runtime/PrimitiveString.h>
  11. #include <LibJS/Runtime/Value.h>
  12. namespace JS {
  13. struct ValueTraits : public Traits<Value> {
  14. static unsigned hash(Value value)
  15. {
  16. VERIFY(!value.is_empty());
  17. if (value.is_string()) {
  18. // FIXME: Propagate this error.
  19. return value.as_string().deprecated_string().hash();
  20. }
  21. if (value.is_bigint())
  22. return value.as_bigint().big_integer().hash();
  23. if (value.is_negative_zero())
  24. value = Value(0);
  25. // In the IEEE 754 standard a NaN value is encoded as any value from 0x7ff0000000000001 to 0x7fffffffffffffff,
  26. // with the least significant bits (referred to as the 'payload') carrying some kind of diagnostic information
  27. // indicating the source of the NaN. Since ECMA262 does not differentiate between different kinds of NaN values,
  28. // Sets and Maps must not differentiate between them either.
  29. // This is achieved by replacing any NaN value by a canonical qNaN.
  30. else if (value.is_nan())
  31. value = js_nan();
  32. return u64_hash(value.encoded()); // FIXME: Is this the best way to hash pointers, doubles & ints?
  33. }
  34. static bool equals(const Value a, const Value b)
  35. {
  36. return same_value_zero(a, b);
  37. }
  38. };
  39. }