TextEncoder.cpp 1.8 KB

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