TextEncoder.cpp 2.1 KB

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