载入中...
搜索中...
未找到
DataModule.cpp
浏览该文件的文档.
1
2
3#include "DataModule.h"
4#include "common/b64.h"
5#include "common/Exception.h"
6#include "HashFunction.h"
7
8#include <simplesquirrel/simplesquirrel.hpp>
9
10#include <Poco/Exception.h>
11#include <Poco/DOM/DOMParser.h>
12#include <Poco/DOM/DOMWriter.h>
13#include <Poco/JSON/Parser.h>
14#include <Poco/JSON/Stringifier.h>
15#include <Poco/XML/XMLWriter.h>
16
17// STL
18#include <cmath>
19#include <functional>
20#include <iostream>
21#include <list>
22#include <sstream>
23
24namespace eve
25{
26namespace data
27{
28
30
31void DataModule::expose(ssq::Table& table)
32{
33 auto cls = table.addClass(name, DataModule::create, false);
34 expose(cls);
35
36 auto json = table.addClass<JsonDocument>(
37 "JsonDocument",
38 std::function<JsonDocument*()>([]() { return new JsonDocument(); }),
39 true);
40 json.addFunc("empty", &JsonDocument::empty);
41 json.addFunc("isObject", &JsonDocument::isObject);
42 json.addFunc("isArray", &JsonDocument::isArray);
43
44 auto xml = table.addClass<XmlDocument>(
45 "XmlDocument",
46 std::function<XmlDocument*()>([]() { return new XmlDocument(); }),
47 true);
48 xml.addFunc("empty", &XmlDocument::empty);
49}
50
51void DataModule::expose(ssq::Class& cls)
52{
53 cls.addFunc("getName", &DataModule::getName);
54 cls.addFunc("newByteData",
55 static_cast<ByteData* (DataModule::*)(size_t)>(&DataModule::newByteData));
56 cls.addFunc("newDataView", &DataModule::newDataView);
57 cls.addFunc("newJsonDocument", &DataModule::newJsonDocument);
58 cls.addFunc("newXmlDocument", &DataModule::newXmlDocument);
59 cls.addFunc("decodeJson",
60 static_cast<JsonDocument* (DataModule::*)(const std::string&)>(&DataModule::decodeJson));
61 cls.addFunc("decodeXml",
62 static_cast<XmlDocument* (DataModule::*)(const std::string&)>(&DataModule::decodeXml));
63 cls.addFunc("encodeJson", &DataModule::encodeJson);
64 cls.addFunc("encodeXml", &DataModule::encodeXml);
65}
66
67} // data
68} // eve
69
70namespace
71{
72
73static const char hexchars[] = "0123456789abcdef";
74
75char *bytesToHex(const uint8_t *src, size_t srclen, size_t &dstlen)
76{
77 dstlen = srclen * 2;
78
79 if (dstlen == 0)
80 return nullptr;
81
82 char *dst = nullptr;
83 try
84 {
85 dst = new char[dstlen + 1];
86 }
87 catch (std::exception &)
88 {
89 throw eve::Exception("Out of memory.");
90 }
91
92 for (size_t i = 0; i < srclen; i++)
93 {
94 uint8_t b = src[i];
95 dst[i * 2 + 0] = hexchars[b >> 4];
96 dst[i * 2 + 1] = hexchars[b & 0xF];
97 }
98
99 dst[dstlen] = '\0';
100 return dst;
101}
102
103uint8_t nibble(char c)
104{
105 if (c >= '0' && c <= '9')
106 return (uint8_t) (c - '0');
107
108 if (c >= 'A' && c <= 'F')
109 return (uint8_t) (c - 'A' + 0x0a);
110
111 if (c >= 'a' && c <= 'f')
112 return (uint8_t) (c - 'a' + 0x0a);
113
114 return 0;
115}
116
117uint8_t *hexToBytes(const char *src, size_t srclen, size_t &dstlen)
118{
119 if (srclen >= 2 && src[0] == '0' && (src[1] == 'x' || src[1] == 'X'))
120 {
121 src += 2;
122 srclen -= 2;
123 }
124
125 dstlen = (srclen + 1) / 2;
126
127 if (dstlen == 0)
128 return nullptr;
129
130 uint8_t *dst = nullptr;
131 try
132 {
133 dst = new uint8_t[dstlen];
134 }
135 catch (std::exception &)
136 {
137 throw eve::Exception("Out of memory.");
138 }
139
140 for (size_t i = 0; i < dstlen; i++)
141 {
142 dst[i] = nibble(src[i * 2]) << 4;
143
144 if (i * 2 + 1 < srclen)
145 dst[i] |= nibble(src[i * 2 + 1]);
146 }
147
148 return dst;
149}
150
151} // anonymous namespace
152
153namespace eve
154{
155namespace data
156{
157
158CompressedData *compress(std::string format, const char *rawbytes, size_t rawsize, int level)
159{
160 Compressor *compressor = Compressor::getCompressor(format);
161
162 if (compressor == nullptr)
163 throw eve::Exception("Invalid compression format.");
164
165 size_t compressedsize = 0;
166 char *cbytes = compressor->compress(format, rawbytes, rawsize, level, compressedsize);
167
168 CompressedData *data = nullptr;
169
170 try
171 {
172 data = new CompressedData(format, cbytes, compressedsize, rawsize, true);
173 }
174 catch (eve::Exception &)
175 {
176 delete[] cbytes;
177 throw;
178 }
179
180 return data;
181}
182
183char *decompress(CompressedData *data, size_t &decompressedsize)
184{
185 size_t rawsize = data->getDecompressedSize();
186
187 char *rawbytes = decompress(data->getFormat(), (const char *) data->getData(),
188 data->getSize(), rawsize);
189
190 decompressedsize = rawsize;
191 return rawbytes;
192}
193
194char *decompress(std::string format, const char *cbytes, size_t compressedsize, size_t &rawsize)
195{
196 Compressor *compressor = Compressor::getCompressor(format);
197
198 if (compressor == nullptr)
199 throw eve::Exception("Invalid compression format.");
200
201 return compressor->decompress(format, cbytes, compressedsize, rawsize);
202}
203
204char *encode(std::string format, const char *src, size_t srclen, size_t &dstlen, size_t linelen)
205{
206 if (format == "hex")
207 return bytesToHex((const uint8_t *) src, srclen, dstlen);
208 else if (format == "base64")
209 return b64_encode(src, srclen, linelen, dstlen);
210 throw eve::Exception("Invalid encoding format.");
211}
212
213char *decode(std::string format, const char *src, size_t srclen, size_t &dstlen)
214{
215 if (format == "hex")
216 return (char *) hexToBytes(src, srclen, dstlen);
217 else if (format == "base64")
218 return b64_decode(src, srclen, dstlen);
219 throw eve::Exception("Invalid encoding format.");
220}
221
222std::string hash(std::string function, Data *input)
223{
224 return hash(function, (const char*) input->getData(), input->getSize());
225}
226
227std::string hash(std::string function, const char *input, uint64_t size)
228{
231 return std::string(output.data, output.size);
232}
233
235{
236 hash(function, (const char*) input->getData(), input->getSize(), output);
237}
238
239void hash(std::string function, const char *input, uint64_t size, HashFunction::Value &output)
240{
242 if (hashfunction == nullptr)
243 throw eve::Exception("Invalid hash function.");
244
245 hashfunction->hash(function, input, size, output);
246}
247
251
255
257{
258 return new DataView(data, offset, size);
259}
260
262{
263 return new ByteData(size);
264}
265
267{
268 return new ByteData(d, size);
269}
270
271ByteData *DataModule::newByteData(void *d, size_t size, bool own)
272{
273 return new ByteData(d, size, own);
274}
275
280
281JsonDocument *DataModule::decodeJson(const std::string &text, std::string *error)
282{
283 try
284 {
285 Poco::JSON::Parser parser;
286 Poco::Dynamic::Var result = parser.parse(text);
287 return new JsonDocument(result);
288 }
289 catch (const Poco::Exception &ex)
290 {
291 if (error)
292 *error = ex.displayText();
293 return nullptr;
294 }
295}
296
298{
299 return decodeJson(text, nullptr);
300}
301
303{
304 if (!data || !data->getData())
305 {
306 if (error)
307 *error = "null data";
308 return nullptr;
309 }
310 std::string text(static_cast<const char *>(data->getData()), data->getSize());
311 return decodeJson(text, error);
312}
313
314std::string DataModule::encodeJson(JsonDocument *doc, bool pretty)
315{
316 if (!doc)
317 return {};
318 try
319 {
320 std::ostringstream oss;
321 int indent = pretty ? 2 : 0;
322 Poco::JSON::Stringifier::stringify(doc->root(), oss, indent);
323 return oss.str();
324 }
325 catch (const Poco::Exception &)
326 {
327 return {};
328 }
329}
330
332{
333 if (!doc)
334 return nullptr;
335 std::string out = encodeJson(doc, pretty);
336 if (out.empty())
337 return nullptr;
338 return new ByteData(out.data(), out.size());
339}
340
345
346XmlDocument *DataModule::decodeXml(const std::string &text, std::string *error)
347{
348 try
349 {
350 Poco::XML::DOMParser parser;
351 Poco::AutoPtr<Poco::XML::Document> pdoc = parser.parseString(text);
352 return new XmlDocument(pdoc);
353 }
354 catch (const Poco::Exception &ex)
355 {
356 if (error)
357 *error = ex.displayText();
358 return nullptr;
359 }
360}
361
363{
364 return decodeXml(text, nullptr);
365}
366
368{
369 if (!data || !data->getData())
370 {
371 if (error)
372 *error = "null data";
373 return nullptr;
374 }
375 std::string text(static_cast<const char *>(data->getData()), data->getSize());
376 return decodeXml(text, error);
377}
378
379std::string DataModule::encodeXml(XmlDocument *doc, bool pretty)
380{
381 if (!doc || !doc->get())
382 return {};
383 try
384 {
385 Poco::XML::DOMWriter writer;
386 if (pretty)
387 writer.setOptions(Poco::XML::XMLWriter::PRETTY_PRINT);
388 std::ostringstream oss;
389 writer.writeNode(oss, doc->get());
390 return oss.str();
391 }
392 catch (const Poco::Exception &)
393 {
394 return {};
395 }
396}
397
399{
400 if (!doc)
401 return nullptr;
402 std::string out = encodeXml(doc, pretty);
403 if (out.empty())
404 return nullptr;
405 return new ByteData(out.data(), out.size());
406}
407
408
409} // data
410} // eve
std::string output
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
std::int32_t c
size_t offset
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
int level
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
std::string error
Definition Package.cpp:174
std::string hash
float d
MigrationFunction function
std::string text
ScriptStructure out
float size
Definition TreeMesh.cpp:158
Data public API.
Definition Data.h:8
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
virtual std::string getName() const =0
Returns the name.
In-memory byte buffer implementing eve::Data (ref-counted).
Definition ByteData.h:13
Stores byte data compressed via DataModule::compress.
Base class for backends for different compression formats.
Definition Compressor.h:15
static Compressor * getCompressor(std::string format)
Gets a Compressor that can compress and decompress a specific format. Returns null if there are no su...
virtual char * compress(std::string format, const char *data, size_t dataSize, int level, size_t &compressedSize)=0
Compresses input data, and returns the compressed result.
virtual char * decompress(std::string format, const char *data, size_t dataSize, size_t &decompressedSize)=0
Decompresses compressed data, and returns the decompressed result.
EVENGINE_API_FOUNDATION public API.
Definition DataModule.h:117
DataModule()
Data module.
virtual ~DataModule()
Data module.
ByteData * encodeXmlData(XmlDocument *doc, bool pretty=false)
Encode xml data.
ByteData * encodeJsonData(JsonDocument *doc, bool pretty=false)
Encode json data.
DataView * newDataView(Data *data, size_t offset, size_t size)
Creates a data view. @ownership Caller deletes unless documented otherwise.
ByteData * newByteData(size_t size)
Creates a byte data. @ownership Caller deletes unless documented otherwise.
std::string encodeXml(XmlDocument *doc, bool pretty=false)
Encode xml.
JsonDocument * decodeJson(const std::string &text)
Decode json.
XmlDocument * decodeXml(const std::string &text)
Decode xml.
XmlDocument * newXmlDocument()
Creates a xml document. @ownership Caller deletes unless documented otherwise.
JsonDocument * newJsonDocument()
Creates a json document. @ownership Caller deletes unless documented otherwise.
std::string encodeJson(JsonDocument *doc, bool pretty=false)
Encode json.
Contains a reference to a subsection of an existing Data object.
Definition DataView.h:16
EVENGINE_API_FOUNDATION public API.
static HashFunction * getHashFunction(std::string function)
Get a HashFunction instance for the given function.
virtual void hash(std::string function, const char *input, uint64_t length, Value &output) const =0
Hash the input, producing an set of bytes as output.
Thin RAII wrapper over a Poco JSON value (object/array/scalar).
bool empty() const
True when the root value is empty.
bool isObject() const
Root type predicates.
bool isArray() const
True when array.
Poco::Dynamic::Var & root()
Underlying Poco dynamic value.
Thin RAII wrapper over a Poco XML DOM document.
Definition XmlDocument.h:12
Poco::XML::Document * get()
Underlying Poco document access.
bool empty() const
True when no underlying document is held.
char * encode(std::string format, const char *src, size_t srclen, size_t &dstlen, size_t linelen)
Encodes raw bytes (e.g. hex / base64) into a text buffer.
CompressedData * compress(std::string format, const char *rawbytes, size_t rawsize, int level)
Compresses a block of memory using the given compression format.
char * decompress(CompressedData *data, size_t &decompressedsize)
Decompresses existing compressed data into raw bytes.
char * decode(std::string format, const char *src, size_t srclen, size_t &dstlen)
Decodes a text buffer (hex / base64) back into raw bytes.
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
char * b64_decode(const char *src, size_t srclen, size_t &size)
Decode base64 encoded data.
Definition b64.cpp:102
char * b64_encode(const char *src, size_t srclen, size_t linelen, size_t &dstlen)
Base64-encode data.
Definition b64.cpp:28