Hashes.h 816 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /*
  2. * Copyright (c) 2019-2020, Andrew Kaster <akaster@serenityos.org>
  3. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/StringView.h>
  9. namespace ELF {
  10. constexpr u32 compute_sysv_hash(StringView name)
  11. {
  12. // SYSV ELF hash algorithm
  13. // Note that the GNU HASH algorithm has less collisions
  14. u32 hash = 0;
  15. for (auto ch : name) {
  16. hash = hash << 4;
  17. hash += ch;
  18. const u32 top_nibble_of_hash = hash & 0xf0000000u;
  19. hash ^= top_nibble_of_hash >> 24;
  20. hash &= ~top_nibble_of_hash;
  21. }
  22. return hash;
  23. }
  24. constexpr u32 compute_gnu_hash(StringView name)
  25. {
  26. // GNU ELF hash algorithm
  27. u32 hash = 5381;
  28. for (auto ch : name)
  29. hash = hash * 33 + ch;
  30. return hash;
  31. }
  32. }