-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynobject.hpp
More file actions
540 lines (479 loc) · 12.2 KB
/
dynobject.hpp
File metadata and controls
540 lines (479 loc) · 12.2 KB
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
/**
* COPYRIGHT 2025 dog0752
* this file is licensed under the dog0752-license-⑨.⑨
*
* this is a single file header only library that implements a
* dynamic object system for C++
*/
#ifndef DYNOBJECT_HPP
#define DYNOBJECT_HPP
#include <any>
#include <expected>
#include <variant>
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
#include <sstream>
#include <iomanip>
namespace dog0752
{
namespace dynobj
{
#ifdef DYNOBJECT_MULTITHREADED
#include <mutex>
#include <shared_mutex>
/* use real mutexes and lock guards */
using factory_mutex_t = std::mutex;
using object_mutex_t = std::shared_mutex;
template <typename T>
using unique_lock_t = std::unique_lock<T>;
template <typename T>
using shared_lock_t = std::shared_lock<T>;
#else
/* dummy, no-op mutexes and locks that do fuckall */
struct DummyMutex
{
}; /* an empty struct */
using factory_mutex_t = DummyMutex;
using object_mutex_t = DummyMutex;
/**
* a lock guard that has an empty constructor/destructor
* the compiler will optimize it away completely hopefully
*/
template <typename T>
struct DummyLock
{
explicit DummyLock(T &)
{
}
};
template <typename T>
using unique_lock_t = DummyLock<T>;
template <typename T>
using shared_lock_t = DummyLock<T>;
#endif
class ObjectFactory
{
private:
class Shape : public std::enable_shared_from_this<Shape>
{
public:
/* constructor for the root shape */
Shape()
: parent_(nullptr), property_key_(0),
offset_(static_cast<size_t>(-1))
{
}
/* constructor for a transition or a child shape */
Shape(std::shared_ptr<const Shape> parent, size_t key)
: parent_(std::move(parent)), property_key_(key),
offset_(parent_->getPropertyCount())
{
}
/* looks up the memory offset for a given property identifier */
std::expected<size_t, std::monostate> getOffset(size_t key) const
{
const Shape *current = this;
/* the root's parent is null, so this loop always terminates */
while (current->parent_)
{
if (current->property_key_ == key)
{
return current->offset_;
}
current = current->parent_.get();
}
return std::unexpected(std::monostate{}); /* signal "not found" */
}
inline size_t getNewOffset() const
{
return offset_;
}
inline size_t getPropertyCount() const
{
return offset_ == static_cast<size_t>(-1) ? 0 : offset_ + 1;
}
private:
friend class ObjectFactory;
/**
* parent_ points to the previous shape in the chain.
* A lookup walks up this chain until it finds the property or
* hits the root.
*/
std::shared_ptr<const Shape> parent_;
/**
* property_key_ is the identifier for the new property that
* this shape
* adds relative to its parent.
*/
size_t property_key_;
/**
* offset_ is the index in the values_ vector where the new
*property is stored.
*/
size_t offset_;
/**
* caches the transition to a new shape when a property is added
*/
std::unordered_map<size_t, std::weak_ptr<Shape>> transitions_;
};
public:
/**
* a unique identifier for a property name, created by interning a
* string
*/
using Identifier = size_t;
class DynObject : public std::enable_shared_from_this<DynObject>
{
public:
using Args = std::vector<std::any>;
using Method = std::function<std::any(DynObject &, Args)>;
/**
* the object's prototype for inheritance. properties not found
* on this object will be looked up on its prototype
*/
std::shared_ptr<DynObject> prototype = nullptr;
template <typename T>
void set(ObjectFactory &factory, Identifier key, T &&value)
{
unique_lock_t<object_mutex_t> lock(mutex_);
auto maybe_offset = shape_->getOffset(key);
if (maybe_offset.has_value())
{
/**
* property already exists. get the offset and update the value
*/
const size_t offset = *maybe_offset;
values_[offset] = std::forward<T>(value);
}
else
{
/* property doesn't exist: this is a shape transition. */
unique_lock_t<factory_mutex_t> factory_lock(
factory.factory_mutex_);
auto new_shape = factory.transition(shape_, key);
shape_ = new_shape;
/**
* pre allocate the vector to the new required
* size. avoids multiple reallocations
*/
values_.resize(new_shape->getPropertyCount());
values_[new_shape->getNewOffset()] = std::forward<T>(value);
}
}
template <typename T>
std::expected<T, std::string> get(Identifier key) const
{
shared_lock_t<object_mutex_t> lock(mutex_);
auto maybe_offset = shape_->getOffset(key);
if (maybe_offset.has_value())
{
const size_t offset = *maybe_offset;
if constexpr (std::is_same_v<T, std::any>)
return values_[offset];
if (const T *val = std::any_cast<T>(&(values_[offset])))
return *val;
return std::unexpected("type mismatch for property");
}
#ifdef DYNOBJECT_MULTITHREADED
lock.unlock(); /* unlock before recursing to mitigate deadlocks */
#endif
if (prototype)
{
return prototype->get<T>(key);
}
return std::unexpected("no such property");
}
template <typename R = std::any>
std::expected<R, std::string> call(Identifier name, Args args = {})
{
auto maybe_method = this->get<Method>(name);
if (!maybe_method.has_value())
{
return std::unexpected(maybe_method.error());
}
const Method &method_to_call = maybe_method.value();
std::any result = method_to_call(*this, std::move(args));
if constexpr (std::is_same_v<R, std::any>)
{
return result;
}
else
{
if (const R *val = std::any_cast<R>(&result))
{
return *val;
}
return std::unexpected("type mismatch for method return value");
}
}
/* JSON serialization */
std::string toJSON(const ObjectFactory &factory)
const /* need factory because of interning */
{
std::ostringstream oss;
oss << "{";
bool first = true;
/* iterate through all interned identifiers */
for (size_t i = 0; i < factory.id_to_str_.size(); ++i)
{
auto maybe_val = this->get<std::any>(i);
if (maybe_val.has_value())
{
if (!first)
oss << ",";
oss << escapeJSONString(std::string(factory.getString(i)))
<< ":" << valueToJSON(*maybe_val);
first = false;
}
}
oss << "}";
return oss.str();
}
/* checks if a property exists directly on this object (not its prototype) */
bool hasProperty(Identifier key) const {
shared_lock_t<object_mutex_t> lock(mutex_);
return shape_->getOffset(key).has_value();
}
/**
* returns a list of all property identifiers on this object
*/
std::vector<Identifier> listProperties() const {
shared_lock_t<object_mutex_t> lock(mutex_);
std::vector<Identifier> keys;
const Shape *current = shape_.get();
/* the root's parent is null, so this loop always terminates */
while (current->parent_) {
keys.push_back(current->property_key_);
current = current->parent_.get();
}
return keys;
}
/**
* returns the type information for a property's value.
* returns typeid(void) if the property does not exist.
*/
const std::type_info &getPropertyType(Identifier key) const {
shared_lock_t<object_mutex_t> lock(mutex_);
auto maybe_offset = shape_->getOffset(key);
if (maybe_offset.has_value()) {
return values_[*maybe_offset].type();
}
#ifdef DYNOBJECT_MULTITHREADED
lock.unlock();
#endif
if (prototype) {
return prototype->getPropertyType(key);
}
return typeid(void);
}
private:
friend class ObjectFactory;
/**
* constructor is private, only the factory can create an object
*/
explicit DynObject(std::shared_ptr<Shape> initial_shape)
: shape_(std::move(initial_shape))
{
}
std::shared_ptr<Shape> shape_;
std::vector<std::any> values_;
mutable object_mutex_t mutex_;
/* --- JSON helpers --- */
static std::string escapeJSONString(const std::string &s)
{
std::ostringstream oss;
oss << "\"";
for (char c : s)
{
switch (c)
{
case '\"':
oss << "\\\"";
break;
case '\\':
oss << "\\\\";
break;
case '\b':
oss << "\\b";
break;
case '\f':
oss << "\\f";
break;
case '\n':
oss << "\\n";
break;
case '\r':
oss << "\\r";
break;
case '\t':
oss << "\\t";
break;
default:
if ((unsigned char)c < 0x20)
{
oss << "\\u" << std::hex << std::setw(4)
<< std::setfill('0') << (int)(unsigned char)c;
}
else
{
oss << c;
}
}
}
oss << "\"";
return oss.str();
}
static std::string valueToJSON(const std::any &val)
{
if (!val.has_value())
return "null";
if (auto p = std::any_cast<int>(&val))
return std::to_string(*p);
if (auto p = std::any_cast<double>(&val))
return std::to_string(*p);
if (auto p = std::any_cast<float>(&val))
return std::to_string(*p);
if (auto p = std::any_cast<bool>(&val))
return *p ? "true" : "false";
if (auto p = std::any_cast<std::string>(&val))
return escapeJSONString(*p);
if (auto p = std::any_cast<const char *>(&val))
return escapeJSONString(*p);
if (auto p = std::any_cast<std::vector<std::any>>(&val))
{
std::ostringstream oss;
oss << "[";
bool first = true;
for (auto &elem : *p)
{
if (!first)
oss << ",";
oss << valueToJSON(elem);
first = false;
}
oss << "]";
return oss.str();
}
if (auto p =
std::any_cast<std::unordered_map<std::string, std::any>>(
&val))
{
std::ostringstream oss;
oss << "{";
bool first = true;
for (auto &[k, v] : *p)
{
if (!first)
oss << ",";
oss << escapeJSONString(k) << ":" << valueToJSON(v);
first = false;
}
oss << "}";
return oss.str();
}
#ifdef __cpp_rtti
return std::string{"<"} + val.type().name() + ">";
#else
return "\"<?>\"";
#endif
}
};
/* FACTORY METHODS */
ObjectFactory() : root_shape_(std::make_shared<Shape>())
{
}
/* creates a new, empty dynamic object */
std::unique_ptr<DynObject> createObject()
{
/**
* use a private constructor via new. std::make_unique cannot
* access it
*/
return std::unique_ptr<DynObject>(new DynObject(root_shape_));
}
Identifier intern(std::string_view str)
{
unique_lock_t<factory_mutex_t> lock(intern_mutex_);
/**
* use transparent hashing to look up string_view without
* creating a string
*/
if (auto it = str_to_id_.find(str); it != str_to_id_.end())
{
return it->second;
}
Identifier id = id_to_str_.size();
id_to_str_.emplace_back(str);
/**
* emplace the string_view from our stable storage (id_to_str_)
* into the map
*/
str_to_id_.emplace(id_to_str_.back(), id);
return id;
}
/**
* retrieves the original string from an interned identifier (for debugging)
*/
std::string_view getString(Identifier id) const
{
unique_lock_t<factory_mutex_t> lock(intern_mutex_);
if (id < id_to_str_.size())
{
return id_to_str_[id];
}
return "<?>";
}
private:
/**
* calculates the new shape an object transitions to when a new property
* is added
*/
std::shared_ptr<Shape> transition(std::shared_ptr<Shape> from,
Identifier key)
{
/* check cache first */
if (auto it = from->transitions_.find(key);
it != from->transitions_.end())
{
if (auto next_shape = it->second.lock())
{
return next_shape;
}
}
auto new_shape = std::make_shared<Shape>(from, key);
/**
* cache the new transition using a weak_ptr to prevent cycles
*/
from->transitions_[key] = new_shape;
return new_shape;
}
/* a transparent hasher for unordered_map lookups with string_view */
struct StringHash
{
using is_transparent = void;
size_t operator()(std::string_view sv) const
{
return std::hash<std::string_view>{}(sv);
}
size_t operator()(const std::string &s) const
{
return std::hash<std::string>{}(s);
}
};
/* factory State */
std::shared_ptr<Shape> root_shape_;
factory_mutex_t factory_mutex_; /* for thread safe shape transitions */
/* string interning state */
mutable factory_mutex_t intern_mutex_;
std::vector<std::string> id_to_str_;
std::unordered_map<std::string, Identifier, StringHash, std::equal_to<>>
str_to_id_;
};
} /* namespace dynobj */
} /* namespace dog0752 */
#endif /* #ifndef DYNOBJECT_HPP */