TextDecoder.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. #include <LibWeb/WebIDL/Buffers.h>
  12. namespace Web::Encoding {
  13. JS_DEFINE_ALLOCATOR(TextDecoder);
  14. WebIDL::ExceptionOr<JS::NonnullGCPtr<TextDecoder>> TextDecoder::construct_impl(JS::Realm& realm, FlyString encoding, Optional<TextDecoderOptions> const& options)
  15. {
  16. auto& vm = realm.vm();
  17. auto decoder = TextCodec::decoder_for(encoding);
  18. if (!decoder.has_value())
  19. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, TRY_OR_THROW_OOM(vm, String::formatted("Invalid encoding {}", encoding)) };
  20. return realm.heap().allocate<TextDecoder>(realm, realm, *decoder, move(encoding), options.value_or({}).fatal, options.value_or({}).ignore_bom);
  21. }
  22. // https://encoding.spec.whatwg.org/#dom-textdecoder
  23. TextDecoder::TextDecoder(JS::Realm& realm, TextCodec::Decoder& decoder, FlyString encoding, bool fatal, bool ignore_bom)
  24. : PlatformObject(realm)
  25. , m_decoder(decoder)
  26. , m_encoding(move(encoding))
  27. , m_fatal(fatal)
  28. , m_ignore_bom(ignore_bom)
  29. {
  30. }
  31. TextDecoder::~TextDecoder() = default;
  32. void TextDecoder::initialize(JS::Realm& realm)
  33. {
  34. Base::initialize(realm);
  35. WEB_SET_PROTOTYPE_FOR_INTERFACE(TextDecoder);
  36. }
  37. // https://encoding.spec.whatwg.org/#dom-textdecoder-decode
  38. WebIDL::ExceptionOr<String> TextDecoder::decode(Optional<JS::Handle<WebIDL::BufferSource>> const& input, Optional<TextDecodeOptions> const&) const
  39. {
  40. if (!input.has_value())
  41. return TRY_OR_THROW_OOM(vm(), m_decoder.to_utf8({}));
  42. // FIXME: Implement the streaming stuff.
  43. auto data_buffer_or_error = WebIDL::get_buffer_source_copy(*input.value()->raw_object());
  44. if (data_buffer_or_error.is_error())
  45. return WebIDL::OperationError::create(realm(), "Failed to copy bytes from ArrayBuffer"_fly_string);
  46. auto& data_buffer = data_buffer_or_error.value();
  47. return TRY_OR_THROW_OOM(vm(), m_decoder.to_utf8({ data_buffer.data(), data_buffer.size() }));
  48. }
  49. }