Blob.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright (c) 2022-2023, Kenneth Myhra <kennethmyhra@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/NonnullRefPtr.h>
  8. #include <AK/Vector.h>
  9. #include <LibWeb/Bindings/BlobPrototype.h>
  10. #include <LibWeb/Bindings/PlatformObject.h>
  11. #include <LibWeb/Forward.h>
  12. #include <LibWeb/WebIDL/ExceptionOr.h>
  13. namespace Web::FileAPI {
  14. using BlobPart = Variant<JS::Handle<WebIDL::BufferSource>, JS::Handle<Blob>, String>;
  15. struct BlobPropertyBag {
  16. String type = String {};
  17. Bindings::EndingType endings;
  18. };
  19. [[nodiscard]] ErrorOr<String> convert_line_endings_to_native(StringView string);
  20. [[nodiscard]] ErrorOr<ByteBuffer> process_blob_parts(Vector<BlobPart> const& blob_parts, Optional<BlobPropertyBag> const& options = {});
  21. [[nodiscard]] bool is_basic_latin(StringView view);
  22. class Blob : public Bindings::PlatformObject {
  23. WEB_PLATFORM_OBJECT(Blob, Bindings::PlatformObject);
  24. JS_DECLARE_ALLOCATOR(Blob);
  25. public:
  26. virtual ~Blob() override;
  27. [[nodiscard]] static JS::NonnullGCPtr<Blob> create(JS::Realm&, ByteBuffer, String type);
  28. [[nodiscard]] static JS::NonnullGCPtr<Blob> create(JS::Realm&, Optional<Vector<BlobPart>> const& blob_parts = {}, Optional<BlobPropertyBag> const& options = {});
  29. static WebIDL::ExceptionOr<JS::NonnullGCPtr<Blob>> construct_impl(JS::Realm&, Optional<Vector<BlobPart>> const& blob_parts = {}, Optional<BlobPropertyBag> const& options = {});
  30. // https://w3c.github.io/FileAPI/#dfn-size
  31. u64 size() const { return m_byte_buffer.size(); }
  32. // https://w3c.github.io/FileAPI/#dfn-type
  33. String const& type() const { return m_type; }
  34. WebIDL::ExceptionOr<JS::NonnullGCPtr<Blob>> slice(Optional<i64> start = {}, Optional<i64> end = {}, Optional<String> const& content_type = {});
  35. WebIDL::ExceptionOr<JS::NonnullGCPtr<Streams::ReadableStream>> stream();
  36. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> text();
  37. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> array_buffer();
  38. ReadonlyBytes bytes() const { return m_byte_buffer.bytes(); }
  39. WebIDL::ExceptionOr<JS::NonnullGCPtr<Streams::ReadableStream>> get_stream();
  40. protected:
  41. Blob(JS::Realm&, ByteBuffer, String type);
  42. Blob(JS::Realm&, ByteBuffer);
  43. virtual void initialize(JS::Realm&) override;
  44. private:
  45. explicit Blob(JS::Realm&);
  46. ByteBuffer m_byte_buffer {};
  47. String m_type {};
  48. };
  49. }