71 lines
1.8 KiB
C++
71 lines
1.8 KiB
C++
|
|
/// @file party/key_io.hpp
|
||
|
|
/// @brief Ship a copyable DPF key as a framed byte blob.
|
||
|
|
#ifndef LIBDPF_PARTY_KEY_IO_HPP__
|
||
|
|
#define LIBDPF_PARTY_KEY_IO_HPP__
|
||
|
|
|
||
|
|
#include <cstdint>
|
||
|
|
#include <cstring>
|
||
|
|
#include <new>
|
||
|
|
#include <stdexcept>
|
||
|
|
#include <utility>
|
||
|
|
#include <vector>
|
||
|
|
|
||
|
|
#include "dpf/net/channel.hpp"
|
||
|
|
#include "dpf/net/trio.hpp"
|
||
|
|
|
||
|
|
namespace dpf
|
||
|
|
{
|
||
|
|
namespace party
|
||
|
|
{
|
||
|
|
|
||
|
|
template <typename Key>
|
||
|
|
void send_key(net::channel & c, const Key & key)
|
||
|
|
{
|
||
|
|
Key copy(key);
|
||
|
|
c.send_bytes(net::msg::dpf_key,
|
||
|
|
reinterpret_cast<const std::uint8_t *>(©), sizeof(Key));
|
||
|
|
}
|
||
|
|
|
||
|
|
template <typename Key>
|
||
|
|
Key recv_key(net::channel & c)
|
||
|
|
{
|
||
|
|
auto body = c.recv_bytes(net::msg::dpf_key);
|
||
|
|
if (body.size() != sizeof(Key))
|
||
|
|
throw std::runtime_error("recv_key size mismatch");
|
||
|
|
alignas(Key) unsigned char raw[sizeof(Key)];
|
||
|
|
std::memcpy(raw, body.data(), sizeof(Key));
|
||
|
|
Key * p = std::launder(reinterpret_cast<Key *>(raw));
|
||
|
|
Key out(std::move(*p));
|
||
|
|
p->~Key();
|
||
|
|
return out;
|
||
|
|
}
|
||
|
|
|
||
|
|
/// @brief Send a key blob through the trio hook (or mesh when unset).
|
||
|
|
template <typename Key>
|
||
|
|
void send_key(net::trio & net, net::role peer, const Key & key)
|
||
|
|
{
|
||
|
|
Key copy(key);
|
||
|
|
net.send_bytes_to(peer, net::msg::dpf_key,
|
||
|
|
reinterpret_cast<const std::uint8_t *>(©), sizeof(Key));
|
||
|
|
}
|
||
|
|
|
||
|
|
/// @brief Receive a key blob through the trio hook (or mesh when unset).
|
||
|
|
template <typename Key>
|
||
|
|
Key recv_key(net::trio & net, net::role peer)
|
||
|
|
{
|
||
|
|
auto body = net.recv_bytes_from(peer, net::msg::dpf_key);
|
||
|
|
if (body.size() != sizeof(Key))
|
||
|
|
throw std::runtime_error("recv_key size mismatch");
|
||
|
|
alignas(Key) unsigned char raw[sizeof(Key)];
|
||
|
|
std::memcpy(raw, body.data(), sizeof(Key));
|
||
|
|
Key * p = std::launder(reinterpret_cast<Key *>(raw));
|
||
|
|
Key out(std::move(*p));
|
||
|
|
p->~Key();
|
||
|
|
return out;
|
||
|
|
}
|
||
|
|
|
||
|
|
} // namespace party
|
||
|
|
} // namespace dpf
|
||
|
|
|
||
|
|
#endif // LIBDPF_PARTY_KEY_IO_HPP__
|