TextEncoder.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. // FIXME: Support `TypedArray::create()` with existing `ArrayBuffer`, so that we don't have to allocate two `ByteBuffer`s.
  25. auto* typed_array = JS::Uint8Array::create(global_object, byte_buffer.size());
  26. typed_array->viewed_array_buffer()->buffer() = move(byte_buffer);
  27. return typed_array;
  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. }