File: value-serializer.hpp

package info (click to toggle)
libzeep 5.1.8-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 3,596 kB
  • sloc: cpp: 27,393; xml: 7,798; javascript: 180; sh: 37; makefile: 8
file content (497 lines) | stat: -rw-r--r-- 17,416 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//        Copyright Maarten L. Hekkelman, 2014-2022
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#pragma once

/*! \file zeep/value-serializer.hpp
	\brief File containing the common serialization code in libzeep

	Serialization in libzeep is used by both the XML and the JSON sub libraries.
	Code that is common is found here.
*/

#include <zeep/config.hpp>

#include <regex>

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>

#include <zeep/exception.hpp>

namespace zeep
{

// --------------------------------------------------------------------
/// \brief A template boilerplate for conversion of basic types to or 
/// from strings.
///
/// Each specialization should provide a static to_string and a from_string
/// method as well as a type_name method. This type_name is used in e.g.
/// constructing WSDL files.

template<typename T, typename = void>
struct value_serializer;

template<>
struct value_serializer<bool>
{
	static constexpr const char* type_name() 				{ return "xsd:boolean"; }
	static std::string to_string(bool value)				{ return value ? "true" : "false"; }
	static bool from_string(const std::string& value)		{ return value == "true" or value == "1" or value == "yes"; }
};

template<>
struct value_serializer<std::string>
{
	static constexpr const char* type_name() 				{ return "xsd:string"; }
	static std::string to_string(const std::string& value)	{ return value; }
	static std::string from_string(const std::string& value){ return value; }
};

template<>
struct value_serializer<int8_t>
{
	static constexpr const char* type_name()				{ return "xsd:byte"; }
	static std::string to_string(int8_t value)				{ return std::to_string(value);	}
	static int8_t from_string(const std::string& value)		{ return static_cast<int8_t>(std::stoi(value)); }
};

template<>
struct value_serializer<uint8_t>
{
	static constexpr const char* type_name()				{ return "xsd:unsignedByte"; }
	static std::string to_string(uint8_t value)				{ return std::to_string(value);	}
	static uint8_t from_string(const std::string& value)	{ return static_cast<uint8_t>(std::stoul(value)); }
};

template<>
struct value_serializer<int16_t>
{
	static constexpr const char* type_name()				{ return "xsd:short"; }
	static std::string to_string(int16_t value)				{ return std::to_string(value);	}
	static int16_t from_string(const std::string& value)	{ return static_cast<int16_t>(std::stoi(value)); }
};

template<>
struct value_serializer<uint16_t>
{
	static constexpr const char* type_name()				{ return "xsd:unsignedShort"; }
	static std::string to_string(uint16_t value)			{ return std::to_string(value);	}
	static uint16_t from_string(const std::string& value)	{ return static_cast<uint16_t>(std::stoul(value)); }
};

template<>
struct value_serializer<int32_t>
{
	static constexpr const char* type_name()				{ return "xsd:int"; }
	static std::string to_string(int32_t value)				{ return std::to_string(value);	}
	static int32_t from_string(const std::string& value)	{ return std::stoi(value); }
};

template<>
struct value_serializer<uint32_t>
{
	static constexpr const char* type_name()				{ return "xsd:unsignedInt"; }
	static std::string to_string(uint32_t value)			{ return std::to_string(value);	}
	static uint32_t from_string(const std::string& value)	{ return static_cast<uint32_t>(std::stoul(value)); }
};

template<>
struct value_serializer<int64_t>
{
	static constexpr const char* type_name()				{ return "xsd:long"; }
	static std::string to_string(int64_t value)				{ return std::to_string(value);	}
	static int64_t from_string(const std::string& value)	{ return static_cast<int64_t>(std::stoll(value)); }
};

template<>
struct value_serializer<uint64_t>
{
	static constexpr const char* type_name()				{ return "xsd:unsignedLong"; }
	static std::string to_string(uint64_t value)			{ return std::to_string(value);	}
	static uint64_t from_string(const std::string& value)	{ return static_cast<uint64_t>(std::stoull(value)); }
};

template<>
struct value_serializer<float>
{
	static constexpr const char* type_name()				{ return "xsd:float"; }
	// static std::string to_string(float value)				{ return std::to_string(value);	}
	static std::string to_string(float value)
	{
		std::ostringstream s;
		s << value;
		return s.str();
	}
	static float from_string(const std::string& value)		{ return std::stof(value); }
};

template<>
struct value_serializer<double>
{
	static constexpr const char* type_name()				{ return "xsd:double"; }
	// static std::string to_string(double value)				{ return std::to_string(value);	}
	static std::string to_string(double value)
	{
		std::ostringstream s;
		s << value;
		return s.str();
	}
	static double from_string(const std::string& value)		{ return std::stod(value); }
};

/// \brief value_serializer for enum values
///
/// This class is used to (de-)serialize enum values. To map enum
/// values to a string you should use the singleton instance
/// accessible through instance() and then call the operator()
/// members assinging each of the enum values with their respective
/// string.
///
/// A recent addition is the init() call to initialize the instance

template<typename T>
struct value_serializer<T, std::enable_if_t<std::is_enum_v<T>>>
{
	std::string m_type_name;

	using value_map_type = std::map<T,std::string>;
	using value_map_value_type = typename value_map_type::value_type;

	value_map_type m_value_map;

	/// \brief Initialize a new instance of value_serializer for this enum, with name and a set of name/value pairs
	static void init(const char* name, std::initializer_list<value_map_value_type> values)
	{
		instance(name).m_value_map = value_map_type(values);
	}

	/// \brief Initialize a new anonymous instance of value_serializer for this enum with a set of name/value pairs
	static void init(std::initializer_list<value_map_value_type> values)
	{
		instance().m_value_map = value_map_type(values);
	}

	static value_serializer& instance(const char* name = nullptr) {
		static value_serializer s_instance;
		if (name and s_instance.m_type_name.empty())
			s_instance.m_type_name = name;
		return s_instance;
	}

	value_serializer& operator()(T v, const std::string& name)
	{
		m_value_map[v] = name;
		return *this;
	}

	value_serializer& operator()(const std::string& name, T v)
	{
		m_value_map[v] = name;
		return *this;
	}

	static const char* type_name()
	{
		return instance().m_type_name;
	}

	static std::string to_string(T value)
	{
		return instance().m_value_map[value];
	}

	static T from_string(const std::string& value)
	{
		T result = {};
		for (auto& t: instance().m_value_map)
			if (t.second == value)
			{
				result = t.first;
				break;
			}
		return result;
	}

	static bool empty()
	{
		return instance().m_value_map.empty();
	}
};

// --------------------------------------------------------------------
// date/time support

/// \brief to_string/from_string for boost::posix_time::ptime
/// boost::posix_time::ptime values are always assumed to be UTC

template<>
struct value_serializer<boost::posix_time::ptime>
{
	static constexpr const char* type_name() { return "xsd:dateTime"; }
	
	/// to_string the boost::posix_time::ptime as YYYY-MM-DDThh:mm:ssZ (zero UTC offset)
	static std::string to_string(const boost::posix_time::ptime& v)
	{
		return boost::posix_time::to_iso_extended_string(v).append("Z");
	}

	/// from_string according to ISO8601 rules.
	/// If Zulu time is specified, then the parsed xsd:dateTime is returned.
	/// If an UTC offset is present, then the offset is subtracted from the xsd:dateTime, this yields UTC.
	/// If no UTC offset is present, then the xsd:dateTime is assumed to be local time and converted to UTC.
	static boost::posix_time::ptime from_string(const std::string& s)
	{
		// We accept 3 general formats:
		//  1: date fields separated with dashes, time fields separated with colons, eg. 2013-02-17T15:25:20,502104+01:00
		//  2: date fields not separated, time fields separated with colons, eg. 20130217T15:25:20,502104+01:00
		//  3: date fields not separated, time fields not separated, eg. 20130217T152520,502104+01:00

		// Apart from the separators, the 3 regexes are basically the same, i.e. they have the same fields
		// Note: std::regex is threadsafe, so we can declare these statically

		// Format 1:
		// ^(-?\d{4})-(\d{2})-(\d{2})T(\d{2})(:(\d{2})(:(\d{2})([.,](\d+))?)?)?((Z)|([-+])(\d{2})(:(\d{2}))?)?$
		//  ^         ^       ^       ^      ^ ^      ^ ^      ^    ^          ^^   ^     ^      ^ ^
		//  |         |       |       |      | |      | |      |    |          ||   |     |      | |
		//  |         |       |       |      | |      | |      |    |          ||   |     |      | [16] UTC minutes offset
		//  |         |       |       |      | |      | |      |    |          ||   |     |      [15] have UTC minutes offset?
		//  |         |       |       |      | |      | |      |    |          ||   |     [14] UTC hour offset
		//  |         |       |       |      | |      | |      |    |          ||   [13] UTC offset sign
		//  |         |       |       |      | |      | |      |    |          |[12] Zulu time
		//  |         |       |       |      | |      | |      |    |          [11] have time zone?
		//  |         |       |       |      | |      | |      |    [10] fractional seconds
		//  |         |       |       |      | |      | |      [9] have fractional seconds
		//  |         |       |       |      | |      | [8] seconds
		//  |         |       |       |      | |      [7] have seconds?
		//  |         |       |       |      | [6] minutes
		//  |         |       |       |      [5] have minutes?
		//  |         |       |       [4] hours
		//  |         |       [3] day
		//  |         [2] month
		//  [1] year
		static std::regex re1("^(-?\\d{4})-(\\d{2})-(\\d{2})T(\\d{2})(:(\\d{2})(:(\\d{2})([.,](\\d+))?)?)?((Z)|([-+])(\\d{2})(:(\\d{2}))?)?$");

		// Format 2:
		// ^(-?\d{4})(\d{2})(\d{2})T(\d{2})(:(\d{2})(:(\d{2})([.,]\d+)?)?)?((Z)|([-+])(\d{2})(:(\d{2}))?)?$
		static std::regex re2("^(-?\\d{4})(\\d{2})(\\d{2})T(\\d{2})(:(\\d{2})(:(\\d{2})([.,]\\d+)?)?)?((Z)|([-+])(\\d{2})(:(\\d{2}))?)?$");

		// Format 3:
		// ^(-?\d{4})(\d{2})(\d{2})T(\d{2})((\d{2})((\d{2})([.,]\d+)?)?)?((Z)|([-+])(\d{2})(:(\d{2}))?)?$
		static std::regex re3("^(-?\\d{4})(\\d{2})(\\d{2})T(\\d{2})((\\d{2})((\\d{2})([.,]\\d+)?)?)?((Z)|([-+])(\\d{2})(:(\\d{2}))?)?$");

		static const int f_year              =  1;
		static const int f_month             =  2;
		static const int f_day               =  3;
		static const int f_hours             =  4;
		static const int f_have_minutes      =  5;
		static const int f_minutes           =  6;
		static const int f_have_seconds      =  7;
		static const int f_seconds           =  8;
		static const int f_have_frac         =  9;
		static const int f_frac              = 10;
		static const int f_have_tz           = 11;
		static const int f_zulu              = 12;
		static const int f_offs_sign         = 13;
		static const int f_offs_hours        = 14;
		static const int f_have_offs_minutes = 15;
		static const int f_offs_minutes      = 16;

		std::smatch m;
		if (not std::regex_match(s, m, re1)) {
			if (not std::regex_match(s, m, re2)) {
				if (not std::regex_match(s, m, re3)) {
					throw exception("Bad dateTime format");
				}
			}
		}

		boost::gregorian::date d(
		  static_cast<uint16_t>(std::stoi(m[f_year]))
		, static_cast<uint16_t>(std::stoi(m[f_month]))
		, static_cast<uint16_t>(std::stoi(m[f_day]))
		);

		int hours = std::stoi(m[f_hours]);
		int minutes = 0, seconds = 0;
		if (m.length(f_have_minutes)) {
			minutes = std::stoi(m[f_minutes]);
			if (m.length(f_have_seconds)) {
				seconds = std::stoi(m[f_seconds]);
			}
		}
		boost::posix_time::time_duration t(hours, minutes, seconds);

		if (m.length(f_have_frac)) {
			double frac = std::stod("0." + m[f_frac].str());
			t += boost::posix_time::microseconds(static_cast<int64_t>((frac + .5) * 1e6));
		}

		boost::posix_time::ptime result = boost::posix_time::ptime(d, t);

		if (m.length(f_have_tz)) {
			if (not m.length(f_zulu)) {
				std::string sign = m[f_offs_sign];
				hours = std::stoi(m[f_offs_hours]);
				minutes = 0;
				if (m.length(f_have_offs_minutes)) {
					minutes = std::stoi(m[f_offs_minutes]);
				}
				boost::posix_time::time_duration offs(hours, minutes, 0);
				if (sign == "+") {
					result -= offs;
				} else {
					result += offs;
				}
			}
		} else {
			// Boost has no clear way of instantiating the *current* timezone, so
			// it's not possible to convert from local to UTC, using boost::local_time classes
			// For now, settle on using mktime...
			std::tm tm = boost::posix_time::to_tm(result);
			tm.tm_isdst = -1;
			std::time_t t2 = mktime(&tm);
			result = boost::posix_time::from_time_t(t2);
		}

		return result;
	}
};

/// \brief to_string/from_string for boost::gregorian::date
/// boost::gregorian::date values are assumed to be floating, i.e. we don't accept timezone info in dates

template<>
struct value_serializer<boost::gregorian::date>
{
	static constexpr const char* type_name() { return "xsd:date"; }

	/// to_string the boost::gregorian::date as YYYY-MM-DD
	static std::string to_string(const boost::gregorian::date& v)
	{
		return boost::gregorian::to_iso_extended_string(v);
	}

	/// from_string boost::gregorian::date according to ISO8601 rules, but without timezone.
	static boost::gregorian::date from_string(const std::string& s)
	{
		// We accept 2 general formats:
		//  1: date fields separated with dashes, eg. 2013-02-17
		//  2: date fields not separated, eg. 20130217

		// Apart from the separators, the 2 regexes are basically the same, i.e. they have the same fields
		// Note: std::regex is threadsafe, so we can declare these statically

		// Format 1:
		// ^(-?\d{4})-(\d{2})-(\d{2})$
		//  ^         ^       ^
		//  |         |       |
		//  |         |       |
		//  |         |       [3] day
		//  |         [2] month
		//  [1] year
		static std::regex re1("^(-?\\d{4})-(\\d{2})-(\\d{2})$");

		// Format 2:
		// ^(-?\d{4})(\d{2})(\d{2})$
		static std::regex re2("^(-?\\d{4})(\\d{2})(\\d{2})$");

		static const int f_year              =  1;
		static const int f_month             =  2;
		static const int f_day               =  3;

		std::smatch m;
		if (not std::regex_match(s, m, re1)) {
			if (not std::regex_match(s, m, re2)) {
				throw exception("Bad date format");
			}
		}

		return boost::gregorian::date(
				  static_cast<uint16_t>(std::stoi(m[f_year]))
				, static_cast<uint16_t>(std::stoi(m[f_month]))
				, static_cast<uint16_t>(std::stoi(m[f_day]))
				);
	}
};

/// \brief to_string/from_string for boost::posix_time::time_duration
/// boost::posix_time::time_duration values are assumed to be floating, i.e. we don't accept timezone info in times

template<>
struct value_serializer<boost::posix_time::time_duration>
{
	static constexpr const char* type_name() { return "xsd:time"; }

	/// to_string the boost::posix_time::time_duration as hh:mm:ss,ffffff
	static std::string to_string(const boost::posix_time::time_duration& v)
	{
		return boost::posix_time::to_simple_string(v);
	}

	/// from_string boost::posix_time::time_duration according to ISO8601 rules, but without timezone.
	static boost::posix_time::time_duration from_string(const std::string& s)
	{
		// We accept 2 general formats:
		//  1: time fields separated with colons, eg. 15:25:20,502104
		//  2: time fields not separated, eg. 152520,502104

		// Apart from the separators, the 2 regexes are basically the same, i.e. they have the same fields
		// Note: std::regex is threadsafe, so we can declare these statically

		// Format 1:
		// ^(\d{2})(:(\d{2})(:(\d{2})([.,](\d+))?)?)?$
		//  ^      ^ ^      ^ ^      ^    ^
		//  |      | |      | |      |    |
		//  |      | |      | |      |    [7] fractional seconds
		//  |      | |      | |      [6] have fractional seconds
		//  |      | |      | [5] seconds
		//  |      | |      [4] have seconds?
		//  |      | [3] minutes
		//  |      [2] have minutes?
		//  [1] hours
		static std::regex re1("^(\\d{2})(:(\\d{2})(:(\\d{2})([.,](\\d+))?)?)?$");

		// Format 2:
		// ^(\d{2})((\d{2})((\d{2})([.,](\d+))?)?)?$
		static std::regex re2("^(\\d{2})((\\d{2})((\\d{2})([.,](\\d+))?)?)?$");

		static const int f_hours             =  1;
		static const int f_have_minutes      =  2;
		static const int f_minutes           =  3;
		static const int f_have_seconds      =  4;
		static const int f_seconds           =  5;
		static const int f_have_frac         =  6;
		static const int f_frac              =  7;

		std::smatch m;
		if (not std::regex_match(s, m, re1)) {
			if (not std::regex_match(s, m, re2)) {
				throw exception("Bad time format");
			}
		}

		int hours = std::stoi(m[f_hours]);
		int minutes = 0, seconds = 0;
		if (m.length(f_have_minutes)) {
			minutes = std::stoi(m[f_minutes]);
			if (m.length(f_have_seconds)) {
				seconds = std::stoi(m[f_seconds]);
			}
		}

		boost::posix_time::time_duration result = boost::posix_time::time_duration(hours, minutes, seconds);

		if (m.length(f_have_frac)) {
			double frac = std::stod(std::string(".").append(std::string(m[f_frac])));
			result += boost::posix_time::microseconds(static_cast<int64_t>((frac + .5) * 1e6));
		}
		
		return result;
	}
};

} // namespace zeep