TextDecoder.cpp 2.2 KB

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