TextEncoder.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 realm.heap().allocate<TextEncoder>(realm, realm);
  15. }
  16. TextEncoder::TextEncoder(JS::Realm& realm)
  17. : PlatformObject(realm)
  18. {
  19. }
  20. TextEncoder::~TextEncoder() = default;
  21. void TextEncoder::initialize(JS::Realm& realm)
  22. {
  23. Base::initialize(realm);
  24. set_prototype(&Bindings::ensure_web_prototype<Bindings::TextEncoderPrototype>(realm, "TextEncoder"));
  25. }
  26. // https://encoding.spec.whatwg.org/#dom-textencoder-encode
  27. JS::Uint8Array* TextEncoder::encode(String const& input) const
  28. {
  29. // 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.
  30. // 1. Convert input to an I/O queue of scalar values.
  31. // 2. Let output be the I/O queue of bytes « end-of-queue ».
  32. // 3. While true:
  33. // 1. Let item be the result of reading from input.
  34. // 2. Let result be the result of processing an item with item, an instance of the UTF-8 encoder, input, output, and "fatal".
  35. // 3. Assert: result is not an error.
  36. // 4. If result is finished, then convert output into a byte sequence and return a Uint8Array object wrapping an ArrayBuffer containing output.
  37. auto byte_buffer = MUST(ByteBuffer::copy(input.bytes()));
  38. auto array_length = byte_buffer.size();
  39. auto array_buffer = JS::ArrayBuffer::create(realm(), move(byte_buffer));
  40. return JS::Uint8Array::create(realm(), array_length, *array_buffer);
  41. }
  42. // https://encoding.spec.whatwg.org/#dom-textencoder-encoding
  43. FlyString const& TextEncoder::encoding()
  44. {
  45. static const FlyString encoding = "utf-8"_fly_string;
  46. return encoding;
  47. }
  48. }