TextEncoder.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/FlyString.h>
  7. #include <LibJS/Runtime/TypedArray.h>
  8. #include <LibWeb/Bindings/Wrapper.h>
  9. #include <LibWeb/Encoding/TextEncoder.h>
  10. #include <LibWeb/HTML/Window.h>
  11. namespace Web::Encoding {
  12. JS::NonnullGCPtr<TextEncoder> TextEncoder::create_with_global_object(HTML::Window& window)
  13. {
  14. return *window.heap().allocate<TextEncoder>(window.realm(), window);
  15. }
  16. TextEncoder::TextEncoder(HTML::Window& window)
  17. : PlatformObject(window.realm())
  18. {
  19. set_prototype(&window.cached_web_prototype("TextEncoder"));
  20. }
  21. TextEncoder::~TextEncoder() = default;
  22. // https://encoding.spec.whatwg.org/#dom-textencoder-encode
  23. JS::Uint8Array* TextEncoder::encode(String const& input) const
  24. {
  25. // NOTE: The AK::String returned from PrimitiveString::string() is always UTF-8, regardless of the internal string type, so most of these steps are no-ops.
  26. // 1. Convert input to an I/O queue of scalar values.
  27. // 2. Let output be the I/O queue of bytes « end-of-queue ».
  28. // 3. While true:
  29. // 1. Let item be the result of reading from input.
  30. // 2. Let result be the result of processing an item with item, an instance of the UTF-8 encoder, input, output, and "fatal".
  31. // 3. Assert: result is not an error.
  32. // 4. If result is finished, then convert output into a byte sequence and return a Uint8Array object wrapping an ArrayBuffer containing output.
  33. auto byte_buffer = input.to_byte_buffer();
  34. auto array_length = byte_buffer.size();
  35. auto* array_buffer = JS::ArrayBuffer::create(realm(), move(byte_buffer));
  36. return JS::Uint8Array::create(realm(), array_length, *array_buffer);
  37. }
  38. // https://encoding.spec.whatwg.org/#dom-textencoder-encoding
  39. FlyString const& TextEncoder::encoding()
  40. {
  41. static FlyString encoding = "utf-8"sv;
  42. return encoding;
  43. }
  44. }