Utf16String.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Copyright (c) 2021-2023, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/ByteString.h>
  8. #include <AK/NonnullRefPtr.h>
  9. #include <AK/RefCounted.h>
  10. #include <AK/Types.h>
  11. #include <AK/Utf16View.h>
  12. #include <AK/Vector.h>
  13. #include <LibJS/Runtime/Completion.h>
  14. namespace JS {
  15. namespace Detail {
  16. class Utf16StringImpl : public RefCounted<Utf16StringImpl> {
  17. public:
  18. ~Utf16StringImpl() = default;
  19. [[nodiscard]] static NonnullRefPtr<Utf16StringImpl> create();
  20. [[nodiscard]] static NonnullRefPtr<Utf16StringImpl> create(Utf16Data);
  21. [[nodiscard]] static NonnullRefPtr<Utf16StringImpl> create(StringView);
  22. [[nodiscard]] static NonnullRefPtr<Utf16StringImpl> create(Utf16View const&);
  23. Utf16Data const& string() const;
  24. Utf16View view() const;
  25. [[nodiscard]] u32 hash() const
  26. {
  27. if (!m_has_hash) {
  28. m_hash = compute_hash();
  29. m_has_hash = true;
  30. }
  31. return m_hash;
  32. }
  33. [[nodiscard]] bool operator==(Utf16StringImpl const& other) const { return string() == other.string(); }
  34. private:
  35. Utf16StringImpl() = default;
  36. explicit Utf16StringImpl(Utf16Data string);
  37. [[nodiscard]] u32 compute_hash() const;
  38. mutable bool m_has_hash { false };
  39. mutable u32 m_hash { 0 };
  40. Utf16Data m_string;
  41. };
  42. }
  43. class Utf16String {
  44. public:
  45. [[nodiscard]] static Utf16String create();
  46. [[nodiscard]] static Utf16String create(Utf16Data);
  47. [[nodiscard]] static Utf16String create(StringView);
  48. [[nodiscard]] static Utf16String create(Utf16View const&);
  49. Utf16Data const& string() const;
  50. Utf16View view() const;
  51. Utf16View substring_view(size_t code_unit_offset, size_t code_unit_length) const;
  52. Utf16View substring_view(size_t code_unit_offset) const;
  53. [[nodiscard]] String to_utf8() const;
  54. [[nodiscard]] ByteString to_byte_string() const;
  55. u16 code_unit_at(size_t index) const;
  56. size_t length_in_code_units() const;
  57. bool is_empty() const;
  58. [[nodiscard]] u32 hash() const { return m_string->hash(); }
  59. [[nodiscard]] bool operator==(Utf16String const& other) const
  60. {
  61. if (m_string == other.m_string)
  62. return true;
  63. return *m_string == *other.m_string;
  64. }
  65. private:
  66. explicit Utf16String(NonnullRefPtr<Detail::Utf16StringImpl>);
  67. NonnullRefPtr<Detail::Utf16StringImpl> m_string;
  68. };
  69. }
  70. namespace AK {
  71. template<>
  72. struct Traits<JS::Utf16String> : public DefaultTraits<JS::Utf16String> {
  73. static unsigned hash(JS::Utf16String const& s) { return s.hash(); }
  74. };
  75. }