File: serialize.hpp

package info (click to toggle)
libzeem 2.1.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 808 kB
  • sloc: cpp: 13,810; xml: 49; makefile: 15; sh: 11
file content (1043 lines) | stat: -rw-r--r-- 27,336 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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
/*-
 * SPDX-License-Identifier: BSD-2-Clause
 *
 * Copyright (c) 2024 Maarten L. Hekkelman
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#pragma once

/**
 * @file
 * definition of the serializer classes used to (de-)serialize XML data.
 */

#include "zeem/config.hpp"
#include "zeem/detail/charconv.hpp"
#include "zeem/node.hpp"

#if ZEEM_USE_DATE_H
# include <date/date.h>
# include <date/tz.h>
#endif

#include <algorithm>
#include <charconv>
#include <chrono>
#include <map>
#include <optional>
#include <regex>
#include <source_location>
#include <string>
#include <system_error>

namespace zeem
{

// --------------------------------------------------------------------
/// \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

template <typename T>
struct value_serializer;

/// @ref value_serializer implementation for booleans
template <>
struct value_serializer<bool>
{
	static constexpr std::string type_name() { return "xsd:boolean"; }
	static constexpr std::string to_string(bool value) { return value ? "true" : "false"; }
	static constexpr bool from_string(std::string_view value) { return value == "true" or value == "1" or value == "yes"; }
};

/// @ref value_serializer implementation for std::strings
template <>
struct value_serializer<std::string>
{
	static constexpr std::string type_name() { return "xsd:string"; }
	static constexpr std::string to_string(std::string value) { return value; }
	static constexpr std::string from_string(std::string_view value) { return std::string{ value }; }
};

/// @ref value_serializer implementation for numbers
template <typename T>
struct char_conv_serializer
{
	using value_type = T;

	static constexpr std::string derived_type_name()
	{
		using value_serializer_type = value_serializer<value_type>;
		return value_serializer_type::type_name();
	}

	static std::string to_string(value_type value)
	{
		char b[32];
		if (auto r = std::to_chars(b, b + sizeof(b), value); r.ec == std::errc{})
			return { b, r.ptr };
		else
			throw std::system_error(std::make_error_code(r.ec), "Error converting value to string for type " + derived_type_name());
	}

	static value_type from_string(std::string_view value)
	{
		value_type result{};

		auto r = from_chars(value.data(), value.data() + value.length(), result);
		if (r.ec != std::errc{} or r.ptr != value.data() + value.length())
			throw std::system_error(std::make_error_code(r.ec), "Error converting value '" + std::string{ value } + "' to type " + derived_type_name());

		return result;
	}
};

/// @ref value_serializer implementation for small int8_t
template <>
struct value_serializer<int8_t> : char_conv_serializer<int8_t>
{
	static std::string type_name() { return "xsd:byte"; }
};

/// @ref value_serializer implementation for uint8_t
template <>
struct value_serializer<uint8_t> : char_conv_serializer<uint8_t>
{
	static std::string type_name() { return "xsd:unsignedByte"; }
};

/// @ref value_serializer implementation for int16_t
template <>
struct value_serializer<int16_t> : char_conv_serializer<int16_t>
{
	static std::string type_name() { return "xsd:short"; }
};

/// @ref value_serializer implementation for uint16_t
template <>
struct value_serializer<uint16_t> : char_conv_serializer<uint16_t>
{
	static std::string type_name() { return "xsd:unsignedShort"; }
};

/// @ref value_serializer implementation for int32_t
template <>
struct value_serializer<int32_t> : char_conv_serializer<int32_t>
{
	static std::string type_name() { return "xsd:int"; }
};

/// @ref value_serializer implementation for uint32_t
template <>
struct value_serializer<uint32_t> : char_conv_serializer<uint32_t>
{
	static std::string type_name() { return "xsd:unsignedInt"; }
};

/// @ref value_serializer implementation for int64_t
template <>
struct value_serializer<int64_t> : char_conv_serializer<int64_t>
{
	static std::string type_name() { return "xsd:long"; }
};

/// @ref value_serializer implementation for uint64_t
template <>
struct value_serializer<uint64_t> : char_conv_serializer<uint64_t>
{
	static std::string type_name() { return "xsd:unsignedLong"; }
};

/// @ref value_serializer implementation for float
template <>
struct value_serializer<float> : char_conv_serializer<float>
{
	static std::string type_name() { return "xsd:float"; }
};

/// @ref value_serializer implementation for double
template <>
struct value_serializer<double> : char_conv_serializer<double>
{
	static std::string type_name() { return "xsd:double"; }
};

/**
 * \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
 */

/** @cond */
template <typename T>
	requires std::is_enum_v<T>
struct value_serializer<T>
{
	using value_map_type = std::map<T, std::string>;
	using value_map_value_type = typename value_map_type::value_type;

  private:
	std::string m_type_name;
	value_map_type m_value_map;

  public:
	/// \brief Initialize a new instance of value_serializer for this enum, with name and a set of name/value pairs
	static void init(std::string_view name, std::initializer_list<value_map_value_type> values)
	{
		instance(std::string{ 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(std::string name = {})
	{
		static value_serializer s_instance;
		if (not name.empty() and s_instance.m_type_name.empty())
			s_instance.m_type_name = std::move(name);
		return s_instance;
	}

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

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

	static std::string type_name()
	{
		return instance().m_type_name;
	}

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

	static T from_string(std::string_view 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();
	}
};

/** @endcond */

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

/// \brief to_string/from_string for std::chrono::system_clock::time_point
/// time is always assumed to be UTC
/// For a specification, see https://www.iso20022.org/standardsrepository/type/ISODateTime

template <>
struct value_serializer<std::chrono::system_clock::time_point>
{
	using time_type = std::chrono::system_clock::time_point;

	static std::string type_name() { return "xsd:dateTime"; }

	/// to_string the time as YYYY-MM-DDThh:mm:ssZ (zero UTC offset)
	static std::string to_string(const time_type &v)
	{
		return std::format("{0:%F}T{0:%T}Z", v);
	}

	/// 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 added to 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 time_type from_string(std::string_view s)
	{
		time_type result;

		std::regex kRX(R"(^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)(Z|([-+]\d{2})(?::(\d{2}))?)?)");
		std::cmatch m;

		if (not std::regex_match(s.data(), s.data() + s.length(), m, kRX))
			throw std::runtime_error("Invalid date format");

		std::istringstream is{ m[1] };

		// Unfortunately, from_stream never seems to return the correct time zone and offset info
		// so we add it ourselves

#if ZEEM_USE_DATE_H
		date::from_stream(is, "%FT%T", result);
#else
		std::chrono::from_stream(is, "%FT%T", result);
#endif

		if (m[2].matched)
		{
			if (m[3].matched)
				result += std::chrono::hours{ stoi(m[3]) };
			if (m[4].matched)
				result += std::chrono::minutes{ stoi(m[4]) };
		}
		else
#if ZEEM_USE_DATE_H
			result = date::zoned_time(date::current_zone(), result).get_sys_time();
#else
			result = std::chrono::zoned_time{ std::chrono::current_zone(), result };
#endif

		if (is.bad() or is.fail())
			throw std::runtime_error("invalid formatted date");

		return result;
	}
};

/// \brief to_string/from_string for std::chrono::sys_days
/// For a specification, see https://www.iso20022.org/standardsrepository/type/ISODateTime

template <>
struct value_serializer<std::chrono::sys_days>
{
	static std::string type_name() { return "xsd:date"; }

	/// to_string the date as YYYY-MM-DD
	static std::string to_string(const std::chrono::sys_days &v)
	{
		return std::format("{:%F}", v);
	}

	/// from_string according to ISO8601 rules.
	static std::chrono::sys_days from_string(std::string_view s)
	{
		std::chrono::sys_days result;

		std::stringstream is;
		is << s;

#if ZEEM_USE_DATE_H
		date::from_stream(is, "%F", result);
#else
		std::chrono::from_stream(is, "%F", result);
#endif

		if (is.bad() or is.fail())
			throw std::runtime_error("invalid formatted date");

		return result;
	}
};

/** @cond */

template <typename T>
using serialize_value_t = decltype(std::declval<value_serializer<T> &>().from_string(std::declval<std::string_view>()));

template <typename T, typename Archive>
using serialize_function = decltype(std::declval<T &>().serialize(std::declval<Archive &>(), std::declval<uint64_t>()));

template <typename T, typename Archive, typename = void>
struct has_serialize : std::false_type
{
};

template <typename T, typename Archive>
	requires(std::is_class_v<T>)
struct has_serialize<T, Archive>
{
	static constexpr bool value = detail::is_detected_v<serialize_function, T, Archive>;
};

template <typename T, typename S>
inline constexpr bool has_serialize_v = has_serialize<T, S>::value;

template <typename T, typename S, typename = void>
struct is_serializable_array_type : std::false_type
{
};

template <typename T>
using value_type_t = typename T::value_type;

template <typename T>
using iterator_t = typename T::iterator;

template <typename T>
using std_string_npos_t = decltype(T::npos);

/// Struct used to detect whether type \a T is serializable
template <typename T, typename S>
struct is_serializable_type
{
	using value_type = std::remove_cvref_t<T>;
	static constexpr bool value =
		detail::is_detected_v<serialize_value_t, value_type> or
		has_serialize_v<value_type, S>;
};

template <typename T, typename S>
inline constexpr bool is_serializable_type_v = is_serializable_type<T, S>::value;

template <typename T, typename S>
	requires(
		detail::is_detected_v<value_type_t, T> and
		detail::is_detected_v<iterator_t, T> and
		not detail::is_detected_v<std_string_npos_t, T>)
struct is_serializable_array_type<T, S>
{
	static constexpr bool value = is_serializable_type_v<typename T::value_type, S>;
};

template <typename T, typename S>
inline constexpr bool is_serializable_array_type_v = is_serializable_array_type<T, S>::value;

/** @endcond */
// --------------------------------------------------------------------

struct serializer;
struct deserializer;

/**
 * @brief base struct to capture named values in a structure for serializing
 */
template <typename T>
class name_value_pair
{
  public:
	/// @brief constructor
	name_value_pair(std::string name, T &value)
		: m_name(std::move(name))
		, m_value(value)
	{
	}

	/** @cond */
	name_value_pair(const name_value_pair &) = default;
	name_value_pair(name_value_pair &&) = default;
	name_value_pair &operator=(const name_value_pair &) = default;
	name_value_pair &operator=(name_value_pair &&) = default;
	/** @endcond */

	[[nodiscard]] const std::string &name() const { return m_name; }
	[[nodiscard]] T &value() const { return m_value; }

	/** @cond */
  private:
	std::string m_name;
	T &m_value;
	/** @endcond */
};

/// @brief name value pair to create elements
template <typename T>
class element_nvp : public name_value_pair<T>
{
  public:
	element_nvp(std::string name, T &value)
		: name_value_pair<T>(std::move(name), value)
	{
	}
};

/// @brief name value pair to create attributes
template <typename T>
class attribute_nvp : public name_value_pair<T>
{
  public:
	attribute_nvp(std::string name, T &value)
		: name_value_pair<T>(std::move(name), value)
	{
	}
};

/**
 * @brief Create a name/value pair for serializing to and from an XML element
 */
template <typename T>
constexpr attribute_nvp<T> make_attribute_nvp(std::string name, T &value)
{
	return attribute_nvp(std::move(name), value);
}

/**
 * @brief Create a name/value pair for serializing to and from an XML attribute
 */
template <typename T>
constexpr element_nvp<T> make_element_nvp(std::string name, T &value)
{
	return element_nvp(std::move(name), value);
}

/**
 * serializer and deserializer are classes that can be used
 * to initiate the serialization. They are the Archive classes that are
 * the first parameter to the templated function 'serialize' in the classes
 * that can be serialized. (See boost::serialization for more info).
 */

/**
 * @brief serializer is the class that initiates the serialization process.
 */

struct serializer
{
	/// @brief constructor, write to \a node
	explicit serializer(element_container &node)
		: m_node(node)
	{
	}

	/** @cond */

	template <typename T>
	serializer &operator&(const element_nvp<T> &rhs)
	{
		return serialize_element(rhs.name(), rhs.value());
	}

	template <typename T>
	serializer &operator&(const attribute_nvp<T> &rhs)
	{
		return serialize_attribute(rhs.name(), rhs.value());
	}

	template <typename T>
	serializer &serialize_element(const T &data);

	template <typename T>
	serializer &serialize_element(std::string_view name, const T &data);

	template <typename T>
	serializer &serialize_attribute(std::string_view name, const T &data);

  private:
	element_container &m_node;

	/** @endcond */
};

/**
 * @brief deserializer is the class that initiates the deserialization process.
 *
 */

struct deserializer
{
	/// @brief constructor, read from \a node
	explicit deserializer(const element_container &node)
		: m_node(node)
	{
	}

	/** @cond */

	template <typename T>
	deserializer &operator&(const element_nvp<T> &rhs)
	{
		return deserialize_element(rhs.name(), rhs.value());
	}

	template <typename T>
	deserializer &operator&(const attribute_nvp<T> &rhs)
	{
		return deserialize_attribute(rhs.name(), rhs.value());
	}

	template <typename T>
	deserializer &deserialize_element(T &data);

	template <typename T>
	deserializer &deserialize_element(std::string_view name, T &data);

	template <typename T>
	deserializer &deserialize_attribute(std::string_view name, T &data);

  private:
	const element_container &m_node;

	/** @endcond */
};

// --------------------------------------------------------------------

/**
 * @brief Type serializer objects can serialize various types,
 * each has its own template specialization.
 */

template <typename T>
struct type_serializer;

/** @cond */

template <typename T, size_t N>
struct type_serializer<T[N]>
{
	using value_type = std::remove_cvref_t<T>;
	using type_serializer_type = type_serializer<value_type>;

	static std::string type_name() { return type_serializer_type::type_name(); }

	static void serialize_child(element_container &n, std::string_view name, const value_type (&value)[N])
	{
		for (const value_type &v : value)
			type_serializer_type::serialize_child(n, name, v);
	}

	static void deserialize_child(const element_container &n, std::string_view name, value_type (&value)[N])
	{
		size_t ix = 0;
		for (auto &e : n)
		{
			if (e.name() != name)
				continue;

			value_type v = {};
			type_serializer_type::deserialize_child(e, ".", v);

			value[ix] = std::move(v);
			++ix;

			if (ix >= N)
				break;
		}
	}
};

template <typename T>
	requires std::is_enum_v<T>
struct type_serializer<T>
	: public value_serializer<T>
{
	using value_type = T;
	using value_serializer_type = value_serializer<T>;
	using value_serializer_type::type_name;

	static std::string serialize_value(const T &value)
	{
		return value_serializer_type::to_string(value);
	}

	static T deserialize_value(std::string_view value)
	{
		return value_serializer_type::from_string(value);
	}

	static void serialize_child(element_container &n, std::string_view name, const value_type &value)
	{
		if (name.empty() or name == ".")
		{
			if (n.type() == node_type::element)
				static_cast<element &>(n).set_content(value_serializer_type::to_string(value));
		}
		else
			n.emplace_back(name)->set_content(value_serializer_type::to_string(value));
	}

	static void deserialize_child(const element_container &n, std::string_view name, value_type &value)
	{
		value = value_type();

		if (name.empty() or name == ".")
		{
			if (n.type() == node_type::element)
				value = value_serializer_type::from_string(static_cast<const element &>(n).get_content());
		}
		else
		{
			auto e = std::find_if(n.begin(), n.end(), [name](auto &e)
				{ return e.name() == name; });
			if (e != n.end())
				value = value_serializer_type::from_string(e->get_content());
		}
	}
};

template <typename T>
	requires has_serialize_v<T, serializer>
struct type_serializer<T>
{
	using value_type = std::remove_cvref_t<T>;

	// the name of this type
	std::string m_type_name;

	static std::string type_name() { return instance().m_type_name.c_str(); }
	void type_name(std::string_view name) { m_type_name = name; }

	static type_serializer &instance()
	{
		static type_serializer s_instance{ std::source_location::current().function_name() };
		return s_instance;
	}

	static void serialize_child(element_container &n, std::string_view name, const value_type &value)
	{
		if (name.empty() or name == ".")
		{
			serializer sr(n);
			const_cast<value_type &>(value).serialize(sr, 0UL);
		}
		else
		{
			element *e = static_cast<element *>(n.emplace_back(name));
			serializer sr(*e);
			const_cast<value_type &>(value).serialize(sr, 0UL);
		}
	}

	static void deserialize_child(const element_container &n, std::string_view name, value_type &value)
	{
		value = value_type();

		if (name.empty() or name == ".")
		{
			deserializer sr(n);
			value.serialize(sr, 0UL);
		}
		else
		{
			auto e = std::find_if(n.begin(), n.end(), [name](auto &e)
				{ return e.name() == name; });
			if (e != n.end())
			{
				deserializer sr(*e);
				value.serialize(sr, 0UL);
			}
		}
	}
};

template <typename T>
struct type_serializer<std::optional<T>>
{
	using value_type = T;
	using container_type = std::optional<value_type>;
	using type_serializer_type = type_serializer<value_type>;

	static std::string type_name() { return type_serializer_type::type_name(); }

	static void serialize_child(element_container &n, std::string_view name, const container_type &value)
	{
		if (value.has_value())
			type_serializer_type::serialize_child(n, name, *value);
	}

	static void deserialize_child(const element_container &n, std::string_view name, container_type &value)
	{
		for (auto &e : n)
		{
			if (e.name() != name)
				continue;

			value_type v = {};
			type_serializer_type::deserialize_child(e, ".", v);
			value.emplace(std::move(v));
		}
	}
};

// nice trick to enforce order in template selection
template <unsigned N>
struct priority_tag /** @cond */ : priority_tag<N - 1> /** @endcond */
{
};

template <>
struct priority_tag<0>
{
};

template <typename T>
	requires is_serializable_array_type_v<T, serializer>
struct type_serializer<T>
{
	using container_type = std::remove_cvref_t<T>;
	using value_type = value_type_t<container_type>;
	using type_serializer_type = type_serializer<value_type>;

	static std::string type_name() { return type_serializer_type::type_name(); }

	static void serialize_child(element_container &n, std::string_view name, const container_type &value)
	{
		for (const value_type &v : value)
			type_serializer_type::serialize_child(n, name, v);
	}

	template <size_t N>
	static auto deserialize_array(const element_container &n, std::string_view name,
		std::array<value_type, N> &value, [[maybe_unused]] priority_tag<2> pt)
	{
		size_t ix = 0;
		for (auto &e : n)
		{
			if (e.name() != name)
				continue;

			value_type v = {};
			type_serializer_type::deserialize_child(e, ".", v);

			value[ix] = std::move(v);
			++ix;

			if (ix >= N)
				break;
		}
	}

	template <typename A>
	static auto deserialize_array(const element_container &n, std::string_view name, A &arr, [[maybe_unused]] priority_tag<1> pt)
		-> decltype(arr.reserve(std::declval<typename container_type::size_type>()),
			void())
	{
		arr.reserve(n.size());

		for (auto &e : n)
		{
			if (e.name() != name)
				continue;

			value_type v = {};
			type_serializer_type::deserialize_child(e, ".", v);

			arr.emplace_back(std::move(v));
		}
	}

	static void deserialize_array(const element_container &n, std::string_view name, container_type &arr, [[maybe_unused]] priority_tag<0> pt)
	{
		for (auto &e : n)
		{
			if (e.name() != name)
				continue;

			value_type v = {};
			type_serializer_type::deserialize_child(e, ".", v);

			arr.emplace_back(std::move(v));
		}
	}

	static void deserialize_child(const element_container &n, std::string_view name, container_type &value)
	{
		type_serializer::deserialize_array(n, name, value, priority_tag<2>{});
	}
};

template <typename T>
struct type_serializer
{
	using value_type = std::remove_cvref_t<T>;
	using value_serializer_type = value_serializer<value_type>;

	static std::string type_name() { return value_serializer_type::type_name(); }

	static std::string serialize_value(const T &value)
	{
		return value_serializer_type::to_string(value);
	}

	static T deserialize_value(std::string_view value)
	{
		return value_serializer_type::from_string(value);
	}

	static void serialize_child(element_container &n, std::string_view name, const value_type &value)
	{
		if (name.empty() or name == ".")
		{
			if (n.type() == node_type::element)
				static_cast<element &>(n).set_content(value_serializer_type::to_string(value));
		}
		else
			n.emplace_back(name)->set_content(value_serializer_type::to_string(value));
	}

	static void deserialize_child(const element_container &n, std::string_view name, value_type &value)
	{
		value = {};

		if (name.empty() or name == ".")
		{
			if (n.type() == node_type::element)
				value = value_serializer_type::from_string(static_cast<const element &>(n).get_content());
		}
		else
		{
			auto e = std::find_if(n.begin(), n.end(), [name](auto &e)
				{ return e.name() == name; });
			if (e != n.end())
				value = value_serializer_type::from_string(e->get_content());
		}
	}
};

// And finally, the implementation of serializer, deserializer and schema_creator.

template <typename T>
serializer &serializer::serialize_element(const T &value)
{
	using value_type = std::remove_cvref_t<T>;
	using type_serializer = type_serializer<value_type>;

	type_serializer::serialize_child(m_node, "", value);

	return *this;
}

template <typename T>
serializer &serializer::serialize_element(std::string_view name, const T &value)
{
	using value_type = std::remove_cvref_t<T>;
	using type_serializer = type_serializer<value_type>;

	type_serializer::serialize_child(m_node, name, value);

	return *this;
}

template <typename T>
serializer &serializer::serialize_attribute(std::string_view name, const T &value)
{
	using value_type = std::remove_cvref_t<T>;
	using type_serializer = type_serializer<value_type>;

	if (m_node.type() == node_type::element)
		static_cast<element &>(m_node).attributes().emplace(name, type_serializer::serialize_value(value));

	return *this;
}

template <typename T>
deserializer &deserializer::deserialize_element(T &value)
{
	using value_type = std::remove_cvref_t<T>;
	using type_serializer = type_serializer<value_type>;

	type_serializer::deserialize_child(m_node, "", value);

	return *this;
}

template <typename T>
deserializer &deserializer::deserialize_element(std::string_view name, T &value)
{
	using value_type = std::remove_cvref_t<T>;
	using type_serializer = type_serializer<value_type>;

	type_serializer::deserialize_child(m_node, name, value);

	return *this;
}

template <typename T>
deserializer &deserializer::deserialize_attribute(std::string_view name, T &value)
{
	using value_type = std::remove_cvref_t<T>;
	using type_serializer = type_serializer<value_type>;

	if (m_node.type() == node_type::element)
	{
		std::string attr = static_cast<const element &>(m_node).get_attribute(name);
		if (not attr.empty())
			value = type_serializer::deserialize_value(attr);
	}
	return *this;
}

/** @endcond */

// --------------------------------------------------------------------
// Convenience routines

/**
 * @brief Write out \a value into XML into document or element \a e
 */

template <typename T>
void to_xml(zeem::element_container &e, const T &value)
{
	serializer sr(e);
	sr.serialize_element(value);
}

/**
 * @brief Write out \a value into XML into document or element \a e
 * using \a name as name for the element to create.
 */

template <typename T>
void to_xml(zeem::element_container &e, std::string_view name, const T &value)
{
	serializer sr(e);
	sr.serialize_element(name, value);
}

/**
 * @brief Read in \a value from the XML in document or element \a e
 */

template <typename T>
void from_xml(const zeem::element_container &e, T &value)
{
	deserializer dsr(e);
	dsr.deserialize_element(value);
}

/**
 * @brief Read in \a value from the XML in document or element \a e
 * using \a name as name for the element to use.
 */

template <typename T>
void from_xml(const zeem::element_container &e, std::string_view name, T &value)
{
	deserializer dsr(e);
	dsr.deserialize_element(name, value);
}

} // namespace zeem