TextEncoder.cpp 1.6 KB

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