ValueTraits.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <andreas@ladybird.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().byte_string().hash();
  20. }
  21. if (value.is_bigint())
  22. return value.as_bigint().big_integer().hash();
  23. // In the IEEE 754 standard a NaN value is encoded as any value from 0x7ff0000000000001 to 0x7fffffffffffffff,
  24. // with the least significant bits (referred to as the 'payload') carrying some kind of diagnostic information
  25. // indicating the source of the NaN. Since ECMA262 does not differentiate between different kinds of NaN values,
  26. // Sets and Maps must not differentiate between them either.
  27. // This is achieved by replacing any NaN value by a canonical qNaN.
  28. if (value.is_nan())
  29. value = js_nan();
  30. return u64_hash(value.encoded()); // FIXME: Is this the best way to hash pointers, doubles & ints?
  31. }
  32. static bool equals(Value const a, Value const b)
  33. {
  34. return same_value(a, b);
  35. }
  36. };
  37. }