refactor
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
#include <ipc/IpcMessage.h>
|
||||
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <unordered_map>
|
||||
|
||||
class RpcInvoker {
|
||||
public:
|
||||
template<typename Obj, typename Ret, typename... Args>
|
||||
void registerMethod(Obj* instance,
|
||||
const std::string& name,
|
||||
Ret (Obj::*method)(Args...)) {
|
||||
handlers[name] =
|
||||
[instance, method](const IpcMessage& req) -> IpcMessage {
|
||||
IpcMessage msg = req;
|
||||
|
||||
// пропустить имя метода
|
||||
(void)msg.template get<std::string>();
|
||||
|
||||
// читать аргументы и вызвать метод
|
||||
return callMethod<Ret, Obj, Args...>(instance, method, msg);
|
||||
};
|
||||
}
|
||||
|
||||
IpcMessage dispatch(const IpcMessage& request) {
|
||||
IpcMessage tmp = request;
|
||||
const std::string method = tmp.get<std::string>();
|
||||
|
||||
auto it = handlers.find(method);
|
||||
if (it == handlers.end()) {
|
||||
return IpcMessage{};
|
||||
}
|
||||
|
||||
return it->second(request);
|
||||
}
|
||||
|
||||
private:
|
||||
template<typename Ret, typename Obj, typename... Args>
|
||||
static IpcMessage callMethod(Obj* obj,
|
||||
Ret (Obj::*method)(Args...),
|
||||
IpcMessage& msg) {
|
||||
auto tuple = readArgs<Args...>(msg);
|
||||
Ret result =
|
||||
std::apply(method, std::tuple_cat(std::make_tuple(obj), tuple));
|
||||
|
||||
IpcMessage out;
|
||||
out.add(result);
|
||||
return out;
|
||||
}
|
||||
|
||||
template<typename... Args>
|
||||
static std::tuple<Args...> readArgs(IpcMessage& msg) {
|
||||
return std::tuple<Args...>{msg.template get<Args>()...};
|
||||
}
|
||||
|
||||
std::unordered_map<std::string,
|
||||
std::function<IpcMessage(const IpcMessage&)>>
|
||||
handlers;
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
class RpcSerializer {
|
||||
public:
|
||||
template<typename T>
|
||||
static void write(std::ostringstream& out, const T& v) {
|
||||
out << v << ' ';
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
static T read(std::istringstream& in) {
|
||||
T v;
|
||||
in >> v;
|
||||
return v;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef __clang__
|
||||
# define RPC_EXPORT __attribute__((annotate("export")))
|
||||
#else
|
||||
# define RPC_EXPORT
|
||||
#endif
|
||||
Reference in New Issue
Block a user