ladybird/Userland/Libraries/LibWeb/WebDriver/Response.cpp
Timothy Flynn 9b483625e6 LibIPC+Everywhere: Change IPC decoders to construct values in-place
Currently, the generated IPC decoders will default-construct the type to
be decoded, then pass that value by reference to the concrete decoder.
This, of course, requires that the type is default-constructible. This
was an issue for decoding Variants, which had to require the first type
in the Variant list is Empty, to ensure it is default constructible.

Further, this made it possible for values to become uninitialized in
user-defined decoders.

This patch makes the decoder interface such that the concrete decoders
themselves contruct the decoded type upon return from the decoder. To do
so, the default decoders in IPC::Decoder had to be moved to the IPC
namespace scope, as these decoders are now specializations instead of
overloaded methods (C++ requires specializations to be in a namespace
scope).
2022-12-26 09:36:16 +01:00

71 lines
1.6 KiB
C++

/*
* Copyright (c) 2022, Tim Flynn <trflynn89@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibIPC/Decoder.h>
#include <LibIPC/Encoder.h>
#include <LibWeb/WebDriver/Response.h>
enum class ResponseType : u8 {
Success,
Error,
};
namespace Web::WebDriver {
Response::Response(JsonValue&& value)
: m_value_or_error(move(value))
{
}
Response::Response(Error&& error)
: m_value_or_error(move(error))
{
}
}
template<>
bool IPC::encode(Encoder& encoder, Web::WebDriver::Response const& response)
{
response.visit(
[](Empty) { VERIFY_NOT_REACHED(); },
[&](JsonValue const& value) {
encoder << ResponseType::Success;
encoder << value;
},
[&](Web::WebDriver::Error const& error) {
encoder << ResponseType::Error;
encoder << error.http_status;
encoder << error.error;
encoder << error.message;
encoder << error.data;
});
return true;
}
template<>
ErrorOr<Web::WebDriver::Response> IPC::decode(Decoder& decoder)
{
auto type = TRY(decoder.decode<ResponseType>());
switch (type) {
case ResponseType::Success:
return TRY(decoder.decode<JsonValue>());
case ResponseType::Error: {
auto http_status = TRY(decoder.decode<unsigned>());
auto error = TRY(decoder.decode<DeprecatedString>());
auto message = TRY(decoder.decode<DeprecatedString>());
auto data = TRY(decoder.decode<Optional<JsonValue>>());
return Web::WebDriver::Error { http_status, move(error), move(message), move(data) };
}
}
VERIFY_NOT_REACHED();
}