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/Encoding/TextDecoder.h>
  9. #include <LibWeb/HTML/Window.h>
  10. #include <LibWeb/WebIDL/AbstractOperations.h>
  11. namespace Web::Encoding {
  12. WebIDL::ExceptionOr<JS::NonnullGCPtr<TextDecoder>> TextDecoder::create_with_global_object(HTML::Window& window, FlyString encoding)
  13. {
  14. auto decoder = TextCodec::decoder_for(encoding);
  15. if (!decoder)
  16. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("Invalid encoding {}", encoding) };
  17. return JS::NonnullGCPtr(*window.heap().allocate<TextDecoder>(window.realm(), window, *decoder, move(encoding), false, false));
  18. }
  19. // https://encoding.spec.whatwg.org/#dom-textdecoder
  20. TextDecoder::TextDecoder(HTML::Window& window, TextCodec::Decoder& decoder, FlyString encoding, bool fatal, bool ignore_bom)
  21. : PlatformObject(window.realm())
  22. , m_decoder(decoder)
  23. , m_encoding(move(encoding))
  24. , m_fatal(fatal)
  25. , m_ignore_bom(ignore_bom)
  26. {
  27. set_prototype(&window.cached_web_prototype("TextDecoder"));
  28. }
  29. TextDecoder::~TextDecoder() = default;
  30. // https://encoding.spec.whatwg.org/#dom-textdecoder-decode
  31. WebIDL::ExceptionOr<String> TextDecoder::decode(JS::Handle<JS::Object> const& input) const
  32. {
  33. // FIXME: Implement the streaming stuff.
  34. auto data_buffer_or_error = WebIDL::get_buffer_source_copy(*input.cell());
  35. if (data_buffer_or_error.is_error())
  36. return DOM::OperationError::create(global_object(), "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. }