summaryrefslogtreecommitdiff
path: root/lib/persistence.h
blob: 05cb49ba3a428cc1ae37af2d193fa423d9a7a05d (plain)
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
#pragma once

#include <charconv>
#include <functional>
#include <glm/glm.hpp>
#include <iosfwd>
#include <map>
#include <memory>
#include <special_members.hpp>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include <vector>

namespace glm {
	template<glm::length_t L, typename T, glm::qualifier Q> struct vec;
}

namespace Persistence {
	struct Selection;
	using SelectionPtr = std::unique_ptr<Selection>;
	using Stack = std::stack<SelectionPtr>;

	struct Writer {
		Writer() = default;
		virtual ~Writer() = default;
		DEFAULT_MOVE_COPY(Writer);

		virtual void beginObject() const = 0;
		virtual void beginArray() const = 0;
		virtual void pushValue(bool value) const = 0;
		virtual void pushValue(float value) const = 0;
		virtual void pushValue(std::nullptr_t) const = 0;
		virtual void pushValue(std::string_view value) const = 0;
		virtual void nextValue() const = 0;
		virtual void pushKey(std::string_view k) const = 0;
		virtual void endArray() const = 0;
		virtual void endObject() const = 0;
	};

	struct Selection {
		Selection() = default;
		virtual ~Selection() = default;
		DEFAULT_MOVE_COPY(Selection);

		virtual void setValue(float);
		virtual void setValue(bool);
		virtual void setValue(std::nullptr_t);
		virtual void setValue(std::string &&);
		virtual void beginArray(Stack &);
		virtual void beginObject(Stack &);
		virtual void endObject(Stack &);
		virtual void beforeValue(Stack &);
		[[nodiscard]] virtual SelectionPtr select(const std::string &);

		[[nodiscard]] virtual bool needsWrite() const;
		virtual void write(const Writer &) const;
	};

	template<typename T> struct SelectionT;

	template<typename T> struct SelectionV : public Selection {
		explicit SelectionV(T & value) : v {value} { }

		void
		beforeValue(Stack &) override
		{
		}

		[[nodiscard]] static SelectionPtr
		make(T & value)
		{
			return make_s<SelectionT<T>>(value);
		}

		template<typename S>
		[[nodiscard]] static SelectionPtr
		make_s(T & value)
		{
			return std::make_unique<S>(value);
		}

		T & v;
	};

	template<typename T>
	concept Scalar = std::is_scalar_v<T>;
	template<typename T>
	concept NotScalar = (!Scalar<T>);

	template<Scalar T> struct SelectionT<T> : public SelectionV<T> {
		using SelectionV<T>::SelectionV;
		using Selection::setValue;

		void
		setValue(T evalue) override
		{
			std::swap(this->v, evalue);
		}

		void
		setValue(std::string && evalue) override
		{
			if constexpr (std::same_as<T, bool>) {
				using namespace std::literals;
				if (!(this->v = evalue == "true"sv)) {
					if (evalue != "false"sv) {
						throw std::runtime_error("Value conversion failure");
					}
				}
			}
			else {
				if (auto res = std::from_chars(evalue.c_str(), evalue.c_str() + evalue.length(), this->v).ec;
						res != std::errc {}) {
					throw std::runtime_error("Value conversion failure");
				}
			}
		}

		void
		write(const Writer & out) const override
		{
			out.pushValue(this->v);
		}
	};

	template<NotScalar T> struct SelectionT<T> : public SelectionV<T> {
		using SelectionV<T>::SelectionV;
		using Selection::setValue;

		void
		setValue(T && evalue) override
		{
			std::swap(this->v, evalue);
		}

		void
		write(const Writer & out) const override
		{
			out.pushValue(this->v);
		}
	};

	struct Persistable;
	struct PersistenceStore {
		PersistenceStore() = default;
		virtual ~PersistenceStore() = default;
		DEFAULT_MOVE_NO_COPY(PersistenceStore);

		template<typename T> [[nodiscard]] inline bool persistType(const T * const, const std::type_info & ti);

		enum class NameAction { Push, HandleAndContinue, Ignore };
		template<typename Helper, typename T>
		[[nodiscard]] inline bool
		persistValue(const std::string_view key, T & value)
		{
			auto s = std::make_unique<Helper>(value);
			const auto act {setName(key, *s)};
			if (act != NameAction::Ignore) {
				sel = std::move(s);
				if (act == NameAction::HandleAndContinue) {
					selHandler();
				}
			}
			return (act != NameAction::Push);
		}

		virtual NameAction setName(const std::string_view key, const Selection &) = 0;
		virtual void selHandler() {};
		virtual void setType(const std::string_view, const Persistable *) = 0;

		SelectionPtr sel {};
	};

	struct PersistenceSelect : public PersistenceStore {
		explicit PersistenceSelect(const std::string & n);

		NameAction setName(const std::string_view key, const Selection &) override;

		void setType(const std::string_view, const Persistable *) override;

		const std::string & name;
	};

	struct PersistenceWrite : public PersistenceStore {
		explicit PersistenceWrite(const Writer & o, bool sh);

		NameAction setName(const std::string_view key, const Selection &) override;

		void selHandler() override;

		void setType(const std::string_view tn, const Persistable * p) override;

		bool first {true};
		const Writer & out;
		bool shared;
	};

	template<glm::length_t L, typename T, glm::qualifier Q>
	struct SelectionT<glm::vec<L, T, Q>> : public SelectionV<glm::vec<L, T, Q>> {
		using V = glm::vec<L, T, Q>;

		struct Members : public SelectionV<V> {
			using SelectionV<V>::SelectionV;

			void
			beforeValue(Stack & stk) override
			{
				stk.push(SelectionV<T>::make(this->v[idx++]));
			}

			glm::length_t idx {0};

			void
			write(const Writer & out) const override
			{
				for (glm::length_t n = 0; n < L; n += 1) {
					if (n) {
						out.nextValue();
					}
					SelectionT<T> {this->v[n]}.write(out);
				}
			}
		};

		using SelectionV<V>::SelectionV;
		using SelectionV<V>::setValue;

		void
		setValue(std::string && s) override
		{
			std::stringstream ss {std::move(s)};
			for (glm::length_t n = 0; n < L; n += 1) {
				ss >> this->v[n];
				ss.get();
			}
		}

		void
		beginArray(Stack & stk) override
		{
			stk.push(this->template make_s<Members>(this->v));
		}

		void
		write(const Writer & out) const override
		{
			out.beginArray();
			Members {this->v}.write(out);
			out.endArray();
		}
	};

	template<typename T> struct SelectionT<std::vector<T>> : public SelectionV<std::vector<T>> {
		using V = std::vector<T>;

		struct Members : public SelectionV<V> {
			using SelectionV<V>::SelectionV;

			void
			beforeValue(Stack & stk) override
			{
				stk.push(SelectionV<T>::make(this->v.emplace_back()));
			}

			void
			write(const Writer & out) const override
			{
				for (auto & member : this->v) {
					if (&member != &this->v.front()) {
						out.nextValue();
					}
					SelectionT<T> {member}.write(out);
				}
			}
		};

		using SelectionV<V>::SelectionV;

		void
		beginArray(Stack & stk) override
		{
			stk.push(this->template make_s<Members>(this->v));
		}

		void
		write(const Writer & out) const override
		{
			out.beginArray();
			Members {this->v}.write(out);
			out.endArray();
		}
	};

	template<typename Map, typename Type = typename Map::mapped_type, auto Key = &Type::element_type::id>
	struct MapByMember : public Persistence::SelectionT<Type> {
		MapByMember(Map & m) : Persistence::SelectionT<Type> {s}, map {m} { }

		using Persistence::SelectionT<Type>::SelectionT;
		void
		endObject(Persistence::Stack & stk) override
		{
			map.emplace(std::invoke(Key, s), std::move(s));
			stk.pop();
		}

	private:
		Type s;
		Map & map;
	};

	template<typename Container, typename Type = typename Container::value_type>
	struct Appender : public Persistence::SelectionT<Type> {
		Appender(Container & c) : Persistence::SelectionT<Type> {s}, container {c} { }
		using Persistence::SelectionT<Type>::SelectionT;
		void
		endObject(Persistence::Stack & stk) override
		{
			container.emplace_back(std::move(s));
			stk.pop();
		}

	private:
		Type s;
		Container & container;
	};

	struct Persistable {
		Persistable() = default;
		virtual ~Persistable() = default;
		DEFAULT_MOVE_COPY(Persistable);

		virtual bool persist(PersistenceStore & store) = 0;

		[[nodiscard]] virtual std::string getId() const;

		template<typename T>
		[[nodiscard]] constexpr static auto
		typeName()
		{
			constexpr std::string_view name {__PRETTY_FUNCTION__};
			constexpr auto s {name.find("T = ") + 4}, e {name.rfind(']')};
			return name.substr(s, e - s);
		}

		template<typename T> static void addFactory() __attribute__((constructor));
		static void addFactory(const std::string_view, std::function<std::unique_ptr<Persistable>()>,
				std::function<std::shared_ptr<Persistable>()>);
		[[nodiscard]] static std::unique_ptr<Persistable> callFactory(const std::string_view);
		[[nodiscard]] static std::shared_ptr<Persistable> callSharedFactory(const std::string_view);
	};

	template<typename T>
	void
	Persistable::addFactory()
	{
		addFactory(typeName<T>(), std::make_unique<T>, std::make_shared<T>);
	}

	template<typename T>
	inline bool
	PersistenceStore::persistType(const T * const v, const std::type_info & ti)
	{
		if constexpr (!std::is_abstract_v<T>) {
			[[maybe_unused]] constexpr auto f = &Persistable::addFactory<T>;
		}
		if (typeid(std::decay_t<T>) == ti) {
			setType(Persistable::typeName<T>(), v);
		}
		return true;
	}

	class ParseBase {
	public:
		using SharedObjects = std::map<std::string, std::shared_ptr<Persistable>>;
		using SharedObjectsWPtr = std::weak_ptr<SharedObjects>;
		using SharedObjectsPtr = std::shared_ptr<SharedObjects>;

		ParseBase();
		DEFAULT_MOVE_NO_COPY(ParseBase);

		template<typename T>
		static auto
		getShared(auto && k)
		{
			return std::dynamic_pointer_cast<T>(Persistence::ParseBase::sharedObjects.lock()->at(k));
		}
		template<typename... T>
		static auto
		emplaceShared(T &&... v)
		{
			return sharedObjects.lock()->emplace(std::forward<T>(v)...);
		}

	protected:
		Stack stk;

	private:
		inline static thread_local SharedObjectsWPtr sharedObjects;
		SharedObjectsPtr sharedObjectsInstance;
	};
	// TODO Move these
	using SeenSharedObjects = std::map<void *, std::string>;
	inline SeenSharedObjects seenSharedObjects;

	template<typename Ptr> struct SelectionPtrBase : public SelectionV<Ptr> {
		static constexpr auto shared = std::is_copy_assignable_v<Ptr>;
		using T = typename Ptr::element_type;
		struct SelectionObj : public SelectionV<Ptr> {
			struct MakeObjectByTypeName : public SelectionV<Ptr> {
				using SelectionV<Ptr>::SelectionV;
				using Selection::setValue;

				void
				setValue(std::string && type) override
				{
					if constexpr (shared) {
						auto no = Persistable::callSharedFactory(type);
						if (auto tno = std::dynamic_pointer_cast<T>(no)) {
							this->v = std::move(tno);
							return;
						}
					}
					else {
						auto no = Persistable::callFactory(type);
						if (dynamic_cast<T *>(no.get())) {
							this->v.reset(static_cast<T *>(no.release()));
							return;
						}
					}
					throw std::runtime_error("Named type doesn't cast to target type");
				}
			};

			struct RememberObjectById : public SelectionV<Ptr> {
				using SelectionV<Ptr>::SelectionV;
				using Selection::setValue;

				void
				setValue(std::string && id) override
				{
					ParseBase::emplaceShared(id, this->v);
				}
			};

			using SelectionV<Ptr>::SelectionV;

			[[nodiscard]] SelectionPtr
			select(const std::string & mbr) override
			{
				using namespace std::literals;
				if (mbr == "p.typeid"sv) {
					if (this->v) {
						throw std::runtime_error("cannot set object type after creation");
					}
					return this->template make_s<MakeObjectByTypeName>(this->v);
				}
				if constexpr (shared) {
					if (mbr == "p.id"sv) {
						make_default_as_needed(this->v);
						return this->template make_s<RememberObjectById>(this->v);
					}
				}
				make_default_as_needed(this->v);
				PersistenceSelect ps {mbr};
				if (this->v->persist(ps)) {
					throw std::runtime_error("cannot find member: " + mbr);
				}
				return std::move(ps.sel);
			}

			void
			endObject(Stack & stk) override
			{
				make_default_as_needed(this->v);
				stk.pop();
			}

			void
			write(const Writer & out) const override
			{
				out.beginObject();
				PersistenceWrite pw {out, shared};
				this->v->persist(pw);
				out.endObject();
			}
		};

		static inline void
		make_default_as_needed(Ptr & v)
		{
			if (!v) {
				if constexpr (std::is_abstract_v<T>) {
					throw std::runtime_error("cannot select member of null abstract object");
				}
				else if constexpr (shared) {
					v = std::make_shared<T>();
				}
				else {
					v = std::make_unique<T>();
				}
			}
		}

		using SelectionV<Ptr>::SelectionV;
		using Selection::setValue;

		void
		setValue(std::nullptr_t) override
		{
			this->v.reset();
		}

		void
		beginObject(Stack & stk) override
		{
			stk.push(this->template make_s<SelectionObj>(this->v));
		}

		void
		endObject(Stack & stk) override
		{
			stk.pop();
		}

		[[nodiscard]] bool
		needsWrite() const override
		{
			return this->v != nullptr;
		}

		void
		write(const Writer & out) const override
		{
			if (this->v) {
				if constexpr (shared) {
					if (const auto existing = seenSharedObjects.find(std::to_address(this->v));
							existing != seenSharedObjects.end()) {
						out.pushValue(existing->second);
						return;
					}
					seenSharedObjects.emplace(std::to_address(this->v), this->v->getId());
				}
				SelectionObj {this->v}.write(out);
			}
			else {
				out.pushValue(nullptr);
			}
		}
	};

	template<typename T> struct SelectionT<std::unique_ptr<T>> : public SelectionPtrBase<std::unique_ptr<T>> {
		using SelectionPtrBase<std::unique_ptr<T>>::SelectionPtrBase;
	};

	template<typename T> struct SelectionT<std::shared_ptr<T>> : public SelectionPtrBase<std::shared_ptr<T>> {
		using SelectionPtrBase<std::shared_ptr<T>>::SelectionPtrBase;
		using SelectionPtrBase<std::shared_ptr<T>>::setValue;

		void
		setValue(std::string && id) override
		{
			if (auto teo = ParseBase::getShared<T>(id)) {
				this->v = std::move(teo);
			}
			else {
				throw std::runtime_error("Named type doesn't cast to target type");
			}
		}
	};
}

#define STORE_TYPE store.persistType(this, typeid(*this))
#define STORE_MEMBER(mbr) STORE_NAME_MEMBER(#mbr, mbr)
#define STORE_NAME_MEMBER(name, mbr) store.persistValue<Persistence::SelectionT<decltype(mbr)>>(name, mbr)
#define STORE_HELPER(mbr, Helper) STORE_NAME_HELPER(#mbr, mbr, Helper)
#define STORE_NAME_HELPER(name, mbr, Helper) store.persistValue<Helper>(name, mbr)