TextDecoder.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright (c) 2022, Ali Mohammad Pur <mpfard@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/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, FlyString encoding)
  13. {
  14. auto& vm = realm.vm();
  15. auto decoder = TextCodec::decoder_for(encoding);
  16. if (!decoder.has_value())
  17. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, TRY_OR_THROW_OOM(vm, String::formatted("Invalid encoding {}", encoding)) };
  18. return realm.heap().allocate<TextDecoder>(realm, realm, *decoder, move(encoding), false, false);
  19. }
  20. // https://encoding.spec.whatwg.org/#dom-textdecoder
  21. TextDecoder::TextDecoder(JS::Realm& realm, TextCodec::Decoder& decoder, FlyString encoding, bool fatal, bool ignore_bom)
  22. : PlatformObject(realm)
  23. , m_decoder(decoder)
  24. , m_encoding(move(encoding))
  25. , m_fatal(fatal)
  26. , m_ignore_bom(ignore_bom)
  27. {
  28. }
  29. TextDecoder::~TextDecoder() = default;
  30. void TextDecoder::initialize(JS::Realm& realm)
  31. {
  32. Base::initialize(realm);
  33. set_prototype(&Bindings::ensure_web_prototype<Bindings::TextDecoderPrototype>(realm, "TextDecoder"));
  34. }
  35. // https://encoding.spec.whatwg.org/#dom-textdecoder-decode
  36. WebIDL::ExceptionOr<String> TextDecoder::decode(Optional<JS::Handle<JS::Object>> const& input) const
  37. {
  38. if (!input.has_value())
  39. return TRY_OR_THROW_OOM(vm(), m_decoder.to_utf8({}));
  40. // FIXME: Implement the streaming stuff.
  41. auto data_buffer_or_error = WebIDL::get_buffer_source_copy(*input->cell());
  42. if (data_buffer_or_error.is_error())
  43. return WebIDL::OperationError::create(realm(), "Failed to copy bytes from ArrayBuffer"_fly_string);
  44. auto& data_buffer = data_buffer_or_error.value();
  45. return TRY_OR_THROW_OOM(vm(), m_decoder.to_utf8({ data_buffer.data(), data_buffer.size() }));
  46. }
  47. }