/*
 * This RPC server stub was autogenerated by idlc (version 8a02fc5d). DO NOT EDIT!
 * Generated from UserClient.idl for interface PciDriverUser at 2021-06-26T17:21:36-0500
 *
 * You should subclass this implementation and define the required abstract methods to complete
 * implementing the interface. Note that there are several helper methods available to simplify
 * this task, or to retrieve more information about the caller.
 *
 * See the full RPC documentation for more details.
 */
#include "Server_PciDriverUser.hpp"
#include "RpcHelpers_PciDriverUser.hpp"

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <stdexcept>

#include <rpc/rt/RpcIoStream.hpp>

using namespace rpc;

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
using Server = PciDriverUserServer;

// stubs for custom type serialization
template<typename... _blah>
constexpr auto TemplatedFalseFlag = false;

/// Given a byte range, decodes the given type
template<typename T>
inline bool deserialize(const std::span<std::byte> &, T &) {
    static_assert(TemplatedFalseFlag<T>, "rpc::deserialize not implemented for custom type");
}
/// Determine how many bytes of memory are required to serialize the given type.
template<typename T>
inline size_t bytesFor(const T &) {
    static_assert(TemplatedFalseFlag<T>, "rpc::bytesFor not implemented for custom type");
}
/// Encodes the given type into the provided region of memory
template<typename T>
inline bool serialize(std::span<std::byte> &, const T &) {
    static_assert(TemplatedFalseFlag<T>, "rpc::serialize not implemented for custom type");
}
/**
 * Creates a new server instance, with the given IO stream.
 */
Server::PciDriverUserServer(const std::shared_ptr<IoStream> &stream) : io(stream) {
}

/**
 * Releases any allocated resources.
 */
Server::~PciDriverUserServer() {
    free(this->txBuf);
}

/**
 * Continuously processes messages until processing fails to receive another message.
 */
bool Server::run(const bool block) {
    bool cont;
    do {
        cont = this->runOne(block);
    } while(cont);
    return cont;
}

/**
 * Reads a single message from the RPC connection and attempts to process it.
 *
 * @return Whether a message was able to be received and processed.
 */
bool Server::runOne(const bool block) {
    // try to receive message
    std::span<std::byte> buf;
    if(!this->io->receive(buf, block)) return false;

    // get the message header and its payload
    if(buf.size() < sizeof(MessageHeader)) {
        this->_HandleError(false, "Received message too small");
        return false;
    }
    const auto hdr = reinterpret_cast<const MessageHeader *>(buf.data());

    const auto payload = buf.subspan(offsetof(MessageHeader, payload));

    // then invoke the appropriate marshalling function
    switch(hdr->type) {
        case static_cast<uint64_t>(internals::Type::GetDeviceAt):
            this->_marshallGetDeviceAt(*hdr, payload);
            break;
        case static_cast<uint64_t>(internals::Type::ReadCfgSpace32):
            this->_marshallReadCfgSpace32(*hdr, payload);
            break;
        case static_cast<uint64_t>(internals::Type::WriteCfgSpace32):
            this->_marshallWriteCfgSpace32(*hdr, payload);
            break;
    }
    return true;
}


// Helper method to build and send a reply message
void Server::_sendReply(const MessageHeader &inHdr, const size_t payloadBytes) {
    const size_t len = sizeof(MessageHeader) + payloadBytes;

    auto hdr = reinterpret_cast<MessageHeader *>(this->txBuf);
    memset(hdr, 0, sizeof(*hdr));
    hdr->type = inHdr.type;
    hdr->flags = MessageHeader::Flags::Response;
    hdr->tag = inHdr.tag;

    const std::span<std::byte> txBufSpan(reinterpret_cast<std::byte *>(this->txBuf), len);
    if(!this->io->reply(txBufSpan)) {
        this->_HandleError(false, "Failed to send RPC reply");
    }
}

// Allocates an aligned transmit buffer of the given size
void Server::_ensureTxBuf(const size_t payloadBytes) {
    const size_t len = sizeof(MessageHeader) + payloadBytes + 16;
    if(len > this->txBufSize) {
        free(this->txBuf);
        int err = posix_memalign(&this->txBuf, 16, len);
        if(err) {
            return this->_HandleError(true, "Failed to allocate RPC send buffer");
        }
        this->txBufSize = len;
    }
}

/**
 * Handles an error that occurred on the server connection. Implementations may override this
 * method if they want to use exceptions, for example.
 *
 * @param fatal If set, the error precludes further operation on this RPC connection
 * @param what Descriptive string for the error
 */
void Server::_HandleError(const bool fatal, const std::string_view &what) {
    fprintf(stderr, "[RPCS] %s: Encountered %s RPC error: %s\n", kServiceName.data(),
        fatal ? "fatal" : "recoverable", what.data());
    if(fatal) exit(-1);
}
/*
 * Autogenerated marshalling method for 'GetDeviceAt' (id $d5b64160331233f1)
 * Have 1 parameter(s), 1 return(s); method is sync
 */
void Server::_marshallGetDeviceAt(const MessageHeader &hdr, const std::span<std::byte> &payload) {
    internals::GetDeviceAtRequest request;
    if(!deserialize(payload, request)) return this->_HandleError(false, "Failed to deserialize request");

    auto retVal = this->implGetDeviceAt(request.address);

    internals::GetDeviceAtResponse reply;
    reply.path = retVal;

    const auto numBytes = bytesFor(reply);
    this->_ensureTxBuf(numBytes);

    auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
    std::span<std::byte> data(packet->payload, numBytes);
    if(!serialize(data, reply)) return this->_HandleError(false, "Failed to serialize reply");

    this->_sendReply(hdr, numBytes);
}
/*
 * Autogenerated marshalling method for 'ReadCfgSpace32' (id $441bae330756a108)
 * Have 2 parameter(s), 1 return(s); method is sync
 */
void Server::_marshallReadCfgSpace32(const MessageHeader &hdr, const std::span<std::byte> &payload) {
    internals::ReadCfgSpace32Request request;
    if(!deserialize(payload, request)) return this->_HandleError(false, "Failed to deserialize request");

    auto retVal = this->implReadCfgSpace32(request.address, request.offset);

    internals::ReadCfgSpace32Response reply;
    reply.result = retVal;

    const auto numBytes = bytesFor(reply);
    this->_ensureTxBuf(numBytes);

    auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
    std::span<std::byte> data(packet->payload, numBytes);
    if(!serialize(data, reply)) return this->_HandleError(false, "Failed to serialize reply");

    this->_sendReply(hdr, numBytes);
}
/*
 * Autogenerated marshalling method for 'WriteCfgSpace32' (id $de92bb2db0b09f5d)
 * Have 3 parameter(s), 0 return(s); method is sync
 */
void Server::_marshallWriteCfgSpace32(const MessageHeader &hdr, const std::span<std::byte> &payload) {
    internals::WriteCfgSpace32Request request;
    if(!deserialize(payload, request)) return this->_HandleError(false, "Failed to deserialize request");

    this->implWriteCfgSpace32(request.address, request.offset, request.value);

    internals::WriteCfgSpace32Response reply;

    const auto numBytes = bytesFor(reply);
    this->_ensureTxBuf(numBytes);

    auto packet = reinterpret_cast<MessageHeader *>(this->txBuf);
    std::span<std::byte> data(packet->payload, numBytes);
    if(!serialize(data, reply)) return this->_HandleError(false, "Failed to serialize reply");

    this->_sendReply(hdr, numBytes);
}
#pragma clang diagnostic pop
