NavigatorDeviceMemory.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /*
  2. * Copyright (c) 2024, Jelle Raaijmakers <jelle@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/BuiltinWrappers.h>
  8. #include <LibCore/System.h>
  9. #include <LibWeb/WebIDL/Types.h>
  10. namespace Web::HTML {
  11. class NavigatorDeviceMemoryMixin {
  12. public:
  13. // https://www.w3.org/TR/device-memory/#computing-device-memory-value
  14. WebIDL::Double device_memory() const
  15. {
  16. // The value is calculated by using the actual device memory in MiB then rounding it to the
  17. // nearest number where only the most signicant bit can be set and the rest are zeros
  18. // (nearest power of two).
  19. auto memory_in_bytes = Core::System::physical_memory_bytes();
  20. auto memory_in_mib = memory_in_bytes / MiB;
  21. auto required_bits = AK::count_required_bits(memory_in_mib);
  22. auto lower_memory_in_mib = static_cast<u64>(1) << (required_bits - 1);
  23. auto upper_memory_in_mib = static_cast<u64>(1) << required_bits;
  24. auto rounded_memory_in_mib = upper_memory_in_mib - memory_in_mib <= memory_in_mib - lower_memory_in_mib
  25. ? upper_memory_in_mib
  26. : lower_memory_in_mib;
  27. // Then dividing that number by 1024.0 to get the value in GiB.
  28. auto memory_in_gib = static_cast<WebIDL::Double>(rounded_memory_in_mib) / 1024.0;
  29. // An upper bound and a lower bound should be set on the list of values.
  30. return AK::clamp(memory_in_gib, 1.0, 4.0);
  31. }
  32. };
  33. }