TextEncoder.cpp 1.6 KB

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