TextEncoder.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /*
  2. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/TypedArray.h>
  7. #include <LibWeb/Bindings/Wrapper.h>
  8. #include <LibWeb/Encoding/TextEncoder.h>
  9. namespace Web::Encoding {
  10. // https://encoding.spec.whatwg.org/#dom-textencoder-encode
  11. JS::Uint8Array* TextEncoder::encode(String const& input) const
  12. {
  13. auto& global_object = wrapper()->global_object();
  14. // 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.
  15. // 1. Convert input to an I/O queue of scalar values.
  16. // 2. Let output be the I/O queue of bytes « end-of-queue ».
  17. // 3. While true:
  18. // 1. Let item be the result of reading from input.
  19. // 2. Let result be the result of processing an item with item, an instance of the UTF-8 encoder, input, output, and "fatal".
  20. // 3. Assert: result is not an error.
  21. // 4. If result is finished, then convert output into a byte sequence and return a Uint8Array object wrapping an ArrayBuffer containing output.
  22. auto byte_buffer = input.to_byte_buffer();
  23. // FIXME: Support `TypedArray::create()` with existing `ArrayBuffer`, so that we don't have to allocate two `ByteBuffer`s.
  24. auto* typed_array = JS::Uint8Array::create(global_object, byte_buffer.size());
  25. typed_array->viewed_array_buffer()->buffer() = move(byte_buffer);
  26. return typed_array;
  27. }
  28. }