DelegateMQ
Loading...
Searching...
No Matches
rapidjson/Serializer.h
Go to the documentation of this file.
1#ifndef SERIALIZER_H
2#define SERIALIZER_H
3
10
12#include "rapidjson/document.h"
13#include "rapidjson/prettywriter.h"
14#include <iostream>
15
16template <class R>
17struct Serializer; // Not defined
18
19// Serialize all target function argument data using serialize class
20template<class RetType, class... Args>
21class Serializer<RetType(Args...)> : public dmq::ISerializer<RetType(Args...)>
22{
23public:
24 // Write arguments to a stream
25 virtual std::ostream& Write(std::ostream& os, Args... args) override {
26 try {
27 os.seekp(0, std::ios::beg);
28 rapidjson::StringBuffer sb;
29 rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(sb);
30
31 (args.Write(writer, os), ...); // C++17 fold expression to write each argument
32
33 if (writer.IsComplete())
34 os << sb.GetString();
35 else
36 os.setstate(std::ios::failbit);
37 }
38 catch (const std::exception& e) {
39 std::cerr << "Serialize error: " << e.what() << std::endl;
40 throw;
41 }
42 return os;
43 }
44
45 // Read arguments from a stream
46 virtual std::istream& Read(std::istream& is, Args&... args) override {
47 try {
48 // Get stream length
49 std::streampos current_pos = is.tellg();
50 is.seekg(0, std::ios::end);
51 int length = static_cast<int>(is.tellg());
52 is.seekg(current_pos, std::ios::beg);
53
54 // Allocate storage buffer
55 char* buf = (char*)malloc(length + 1);
56 if (!buf)
57 return is;
58
59 // Copy into buffer
60 is.rdbuf()->sgetn(buf, length);
61 buf[length] = 0; // null terminate incoming data
62
63 //std::cout << buf;
64
65 // Parse JSON
66 rapidjson::Document doc;
67 doc.Parse(buf);
68 free(buf);
69
70 // Check for parsing errors
71 if (doc.HasParseError())
72 {
73 // Let caller know read failed
74 is.setstate(std::ios::failbit);
75 std::cout << "Parse error: " << doc.GetParseError() << std::endl;
76 std::cout << "Error offset: " << doc.GetErrorOffset() << std::endl;
77 return is;
78 }
79
80 (args.Read(doc, is), ...); // C++17 fold expression to read each argument
81 return is;
82 }
83 catch (const std::exception& e) {
84 std::cerr << "Deserialize error: " << e.what() << std::endl;
85 throw;
86 }
87 return is;
88 }
89};
90
91#endif
Delegate serializer interface class.
virtual std::istream & Read(std::istream &is, Args &... args) override
Definition rapidjson/Serializer.h:46
virtual std::ostream & Write(std::ostream &os, Args... args) override
Definition rapidjson/Serializer.h:25
Definition bitsery/Serializer.h:24
Definition ISerializer.h:12