ladybird/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp
Linus Groh fc9d587e39 LibJS: Make PromiseCapability GC-allocated
A struct with three raw pointers to other GC'd types is a pretty big
liability, let's just turn this into a Cell itself.
This comes with the additional benefit of being able to capture it in
a lambda effortlessly, without having to create handles for individual
members.
2022-10-02 23:02:27 +01:00

57 lines
1.8 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibJS/Runtime/PromiseCapability.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
#include <LibWeb/WebIDL/Promise.h>
namespace Web::Fetch::Infrastructure {
Body::Body(JS::Handle<Streams::ReadableStream> stream)
: m_stream(move(stream))
{
}
Body::Body(JS::Handle<Streams::ReadableStream> stream, SourceType source, Optional<u64> length)
: m_stream(move(stream))
, m_source(move(source))
, m_length(move(length))
{
}
// https://fetch.spec.whatwg.org/#concept-body-clone
WebIDL::ExceptionOr<Body> Body::clone() const
{
// To clone a body body, run these steps:
auto& vm = Bindings::main_thread_vm();
auto& realm = *vm.current_realm();
// FIXME: 1. Let « out1, out2 » be the result of teeing bodys stream.
// FIXME: 2. Set bodys stream to out1.
auto* out2 = vm.heap().allocate<Streams::ReadableStream>(realm, realm);
// 3. Return a body whose stream is out2 and other members are copied from body.
return Body { JS::make_handle(out2), m_source, m_length };
}
// https://fetch.spec.whatwg.org/#fully-reading-body-as-promise
JS::NonnullGCPtr<JS::PromiseCapability> Body::fully_read_as_promise() const
{
auto& vm = Bindings::main_thread_vm();
auto& realm = *vm.current_realm();
// FIXME: Implement the streams spec - this is completely made up for now :^)
if (auto const* byte_buffer = m_source.get_pointer<ByteBuffer>()) {
auto result = String::copy(*byte_buffer);
return WebIDL::create_resolved_promise(realm, JS::js_string(vm, move(result)));
}
// Empty, Blob, FormData
return WebIDL::create_rejected_promise(realm, JS::InternalError::create(realm, "Reading body isn't fully implemented"sv));
}
}