TextDecoder.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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/IDLAbstractOperations.h>
  9. #include <LibWeb/Bindings/Wrapper.h>
  10. #include <LibWeb/Encoding/TextDecoder.h>
  11. #include <LibWeb/HTML/Window.h>
  12. namespace Web::Encoding {
  13. DOM::ExceptionOr<JS::NonnullGCPtr<TextDecoder>> TextDecoder::create_with_global_object(HTML::Window& window, FlyString encoding)
  14. {
  15. auto decoder = TextCodec::decoder_for(encoding);
  16. if (!decoder)
  17. return DOM::SimpleException { DOM::SimpleExceptionType::TypeError, String::formatted("Invalid encoding {}", encoding) };
  18. return JS::NonnullGCPtr(*window.heap().allocate<TextDecoder>(window.realm(), window, *decoder, move(encoding), false, false));
  19. }
  20. // https://encoding.spec.whatwg.org/#dom-textdecoder
  21. TextDecoder::TextDecoder(HTML::Window& window, TextCodec::Decoder& decoder, FlyString encoding, bool fatal, bool ignore_bom)
  22. : PlatformObject(window.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. // https://encoding.spec.whatwg.org/#dom-textdecoder-decode
  31. DOM::ExceptionOr<String> TextDecoder::decode(JS::Handle<JS::Object> const& input) const
  32. {
  33. // FIXME: Implement the streaming stuff.
  34. auto data_buffer_or_error = Bindings::IDL::get_buffer_source_copy(*input.cell());
  35. if (data_buffer_or_error.is_error())
  36. return DOM::OperationError::create("Failed to copy bytes from ArrayBuffer");
  37. auto& data_buffer = data_buffer_or_error.value();
  38. return m_decoder.to_utf8({ data_buffer.data(), data_buffer.size() });
  39. }
  40. }