Serenity Operating System
1/*
2 * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <AK/DeprecatedFlyString.h>
8#include <LibJS/Runtime/TypedArray.h>
9#include <LibWeb/Bindings/Intrinsics.h>
10#include <LibWeb/Encoding/TextEncoder.h>
11#include <LibWeb/WebIDL/ExceptionOr.h>
12
13namespace Web::Encoding {
14
15WebIDL::ExceptionOr<JS::NonnullGCPtr<TextEncoder>> TextEncoder::construct_impl(JS::Realm& realm)
16{
17 return MUST_OR_THROW_OOM(realm.heap().allocate<TextEncoder>(realm, realm));
18}
19
20TextEncoder::TextEncoder(JS::Realm& realm)
21 : PlatformObject(realm)
22{
23}
24
25TextEncoder::~TextEncoder() = default;
26
27JS::ThrowCompletionOr<void> TextEncoder::initialize(JS::Realm& realm)
28{
29 MUST_OR_THROW_OOM(Base::initialize(realm));
30 set_prototype(&Bindings::ensure_web_prototype<Bindings::TextEncoderPrototype>(realm, "TextEncoder"));
31
32 return {};
33}
34
35// https://encoding.spec.whatwg.org/#dom-textencoder-encode
36JS::Uint8Array* TextEncoder::encode(DeprecatedString const& input) const
37{
38 // NOTE: The AK::DeprecatedString returned from PrimitiveString::string() is always UTF-8, regardless of the internal string type, so most of these steps are no-ops.
39
40 // 1. Convert input to an I/O queue of scalar values.
41 // 2. Let output be the I/O queue of bytes « end-of-queue ».
42 // 3. While true:
43 // 1. Let item be the result of reading from input.
44 // 2. Let result be the result of processing an item with item, an instance of the UTF-8 encoder, input, output, and "fatal".
45 // 3. Assert: result is not an error.
46 // 4. If result is finished, then convert output into a byte sequence and return a Uint8Array object wrapping an ArrayBuffer containing output.
47
48 auto byte_buffer = input.to_byte_buffer();
49 auto array_length = byte_buffer.size();
50 auto array_buffer = JS::ArrayBuffer::create(realm(), move(byte_buffer));
51 return JS::Uint8Array::create(realm(), array_length, *array_buffer);
52}
53
54// https://encoding.spec.whatwg.org/#dom-textencoder-encoding
55DeprecatedFlyString const& TextEncoder::encoding()
56{
57 static DeprecatedFlyString encoding = "utf-8"sv;
58 return encoding;
59}
60
61}