TextDecoder.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright (c) 2022, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Forward.h>
  8. #include <AK/NonnullRefPtr.h>
  9. #include <AK/RefCounted.h>
  10. #include <LibJS/Forward.h>
  11. #include <LibTextCodec/Decoder.h>
  12. #include <LibWeb/Bindings/Wrappable.h>
  13. #include <LibWeb/DOM/ExceptionOr.h>
  14. #include <LibWeb/Forward.h>
  15. namespace Web::Encoding {
  16. // https://encoding.spec.whatwg.org/#textdecoder
  17. class TextDecoder
  18. : public RefCounted<TextDecoder>
  19. , public Bindings::Wrappable {
  20. public:
  21. using WrapperType = Bindings::TextDecoderWrapper;
  22. static DOM::ExceptionOr<NonnullRefPtr<TextDecoder>> create(FlyString encoding)
  23. {
  24. auto decoder = TextCodec::decoder_for(encoding);
  25. if (!decoder)
  26. return DOM::SimpleException { DOM::SimpleExceptionType::TypeError, String::formatted("Invalid encoding {}", encoding) };
  27. return adopt_ref(*new TextDecoder(*decoder, move(encoding), false, false));
  28. }
  29. static DOM::ExceptionOr<NonnullRefPtr<TextDecoder>> create_with_global_object(Bindings::WindowObject&, FlyString label)
  30. {
  31. return TextDecoder::create(move(label));
  32. }
  33. DOM::ExceptionOr<String> decode(JS::Handle<JS::Object> const&) const;
  34. FlyString const& encoding() const { return m_encoding; }
  35. bool fatal() const { return m_fatal; }
  36. bool ignore_bom() const { return m_ignore_bom; };
  37. protected:
  38. // https://encoding.spec.whatwg.org/#dom-textdecoder
  39. TextDecoder(TextCodec::Decoder& decoder, FlyString encoding, bool fatal, bool ignore_bom)
  40. : m_decoder(decoder)
  41. , m_encoding(move(encoding))
  42. , m_fatal(fatal)
  43. , m_ignore_bom(ignore_bom)
  44. {
  45. }
  46. TextCodec::Decoder& m_decoder;
  47. FlyString m_encoding;
  48. bool m_fatal { false };
  49. bool m_ignore_bom { false };
  50. };
  51. }