mirror of
https://codeberg.org/DawnMagnet/reflect-cpp
synced 2026-12-06 02:36:18 +08:00
Use exceptions inside the writers (#535)
Adds error handling using exceptions in the write processes.
This commit is contained in:
@@ -6,6 +6,7 @@
|
||||
#include <ostream>
|
||||
|
||||
#include "../Processors.hpp"
|
||||
#include "../Result.hpp"
|
||||
#include "../parsing/Parent.hpp"
|
||||
#include "Parser.hpp"
|
||||
|
||||
@@ -13,7 +14,7 @@ namespace rfl::msgpack {
|
||||
|
||||
/// Returns msgpack bytes.
|
||||
template <class... Ps>
|
||||
std::vector<char> write(const auto& _obj) noexcept {
|
||||
std::vector<char> write(const auto& _obj) {
|
||||
using T = std::remove_cvref_t<decltype(_obj)>;
|
||||
using ParentType = parsing::Parent<Writer>;
|
||||
msgpack_sbuffer sbuf;
|
||||
@@ -21,15 +22,21 @@ std::vector<char> write(const auto& _obj) noexcept {
|
||||
msgpack_packer pk;
|
||||
msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
|
||||
auto w = Writer(&pk);
|
||||
Parser<T, Processors<Ps...>>::write(w, _obj, typename ParentType::Root{});
|
||||
auto bytes = std::vector<char>(sbuf.data, sbuf.data + sbuf.size);
|
||||
const auto bytes = [&]() -> Result<std::vector<char>> {
|
||||
try {
|
||||
Parser<T, Processors<Ps...>>::write(w, _obj, typename ParentType::Root{});
|
||||
return std::vector<char>(sbuf.data, sbuf.data + sbuf.size);
|
||||
} catch (const std::exception& e) {
|
||||
return error(e.what());
|
||||
}
|
||||
}();
|
||||
msgpack_sbuffer_destroy(&sbuf);
|
||||
return bytes;
|
||||
return bytes.value();
|
||||
}
|
||||
|
||||
/// Writes a MSGPACK into an ostream.
|
||||
template <class... Ps>
|
||||
std::ostream& write(const auto& _obj, std::ostream& _stream) noexcept {
|
||||
std::ostream& write(const auto& _obj, std::ostream& _stream) {
|
||||
auto buffer = write<Ps...>(_obj);
|
||||
_stream.write(buffer.data(), buffer.size());
|
||||
return _stream;
|
||||
|
||||
Reference in New Issue
Block a user