TextDecoder.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * Copyright (c) 2022, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/DeprecatedFlyString.h>
  7. #include <LibJS/Runtime/TypedArray.h>
  8. #include <LibWeb/Bindings/Intrinsics.h>
  9. #include <LibWeb/Encoding/TextDecoder.h>
  10. #include <LibWeb/WebIDL/AbstractOperations.h>
  11. namespace Web::Encoding {
  12. WebIDL::ExceptionOr<JS::NonnullGCPtr<TextDecoder>> TextDecoder::construct_impl(JS::Realm& realm, DeprecatedFlyString encoding)
  13. {
  14. auto decoder = TextCodec::decoder_for(encoding);
  15. if (!decoder.has_value())
  16. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, DeprecatedString::formatted("Invalid encoding {}", encoding) };
  17. return MUST_OR_THROW_OOM(realm.heap().allocate<TextDecoder>(realm, realm, *decoder, move(encoding), false, false));
  18. }
  19. // https://encoding.spec.whatwg.org/#dom-textdecoder
  20. TextDecoder::TextDecoder(JS::Realm& realm, TextCodec::Decoder& decoder, DeprecatedFlyString encoding, bool fatal, bool ignore_bom)
  21. : PlatformObject(realm)
  22. , m_decoder(decoder)
  23. , m_encoding(move(encoding))
  24. , m_fatal(fatal)
  25. , m_ignore_bom(ignore_bom)
  26. {
  27. }
  28. TextDecoder::~TextDecoder() = default;
  29. JS::ThrowCompletionOr<void> TextDecoder::initialize(JS::Realm& realm)
  30. {
  31. MUST_OR_THROW_OOM(Base::initialize(realm));
  32. set_prototype(&Bindings::ensure_web_prototype<Bindings::TextDecoderPrototype>(realm, "TextDecoder"));
  33. return {};
  34. }
  35. // https://encoding.spec.whatwg.org/#dom-textdecoder-decode
  36. WebIDL::ExceptionOr<DeprecatedString> TextDecoder::decode(JS::Handle<JS::Object> const& input) const
  37. {
  38. // FIXME: Implement the streaming stuff.
  39. auto data_buffer_or_error = WebIDL::get_buffer_source_copy(*input.cell());
  40. if (data_buffer_or_error.is_error())
  41. return WebIDL::OperationError::create(realm(), "Failed to copy bytes from ArrayBuffer");
  42. auto& data_buffer = data_buffer_or_error.value();
  43. return m_decoder.to_utf8({ data_buffer.data(), data_buffer.size() });
  44. }
  45. }