-
Notifications
You must be signed in to change notification settings - Fork 0
/
GarbageCollection.h
8934 lines (7190 loc) · 295 KB
/
GarbageCollection.h
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
#ifndef DRAGAZO_GARBAGE_COLLECT_H
#define DRAGAZO_GARBAGE_COLLECT_H
#include <iostream>
#include <utility>
#include <mutex>
#include <atomic>
#include <new>
#include <type_traits>
#include <thread>
#include <chrono>
#include <algorithm>
#include <exception>
#include <stdexcept>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <climits>
#include <typeinfo>
#include <iterator>
#include <functional>
#include <memory>
#include <tuple>
#include <array>
#include <vector>
#include <deque>
#include <forward_list>
#include <list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <queue>
#include <variant>
#include <optional>
// --------------------- //
// -- cpp-gc settings -- //
// --------------------- //
// controls if extra undefined behavior checks are performed at runtime for user-level code.
// these help safeguard some common und cases at the expense of runtime performance.
// however, if you're sure you never invoke undefined behavior, disabling these could give more performant code.
// at the very least i suggest leaving them on during development and for testing.
// non-zero enables these additional checks - zero disables them.
#define DRAGAZO_GARBAGE_COLLECT_EXTRA_UND_CHECKS 1
// if nonzero, several debugging features are enabled:
// 1) GC::ptr will be set to null upon destruction
#define DRAGAZO_GARBAGE_COLLECT_DEBUGGING_FEATURES 1
// to ease mutex contention among threads, cpp-gc allows you to partition threads into specific disjunction groups for gc.
// only threads in the same disjunction can share objects - it is undefined behavior to violate this.
// if this setting is nonzero, violating disjunction boundaries results in an exception in the violating thread instead of undefined behavior.
// this only applies to pointing a GC::ptr at an object from a different object disjunction set.
// you could potentially also violate this by using raw pointers to access the object (or even worse - add mutable roots to it) - THESE CASES ARE NOT CHECKED.
// because violating gc disjunctions is particularly-bad undefined behavior I HIGHLY SUGGEST YOU LEAVE THIS ON ALWAYS!!
// however, if you're SUPER DUPER confident you don't violate this, you can disable it to save space and time (not worth the risk).
// e.g. if your program will only ever run on a single thread this can safely be disabled with no chance of violation.
#define DRAGAZO_GARBAGE_COLLECT_DISJUNCTION_SAFETY_CHECKS 1
// the default type of lockable to use in wrappers.
// i suggest you use some form of recursive mutex - otherwise e.g. a wrapped container's element type could collect under a lock and deadlock.
// if you want some other type for a specific object, you should use the available template utilities instead of changing this globally.
typedef std::recursive_mutex __gc_default_wrapper_lockable_t;
// -------------------------------- //
// -- utility types forward decl -- //
// -------------------------------- //
// don't use these directly - use their aliases in the GC class.
// e.g. don't use __gc_vector, use GC::vector.
template<typename T, typename Deleter, typename Lockable>
class __gc_unique_ptr;
template<typename T, typename Allocator, typename Lockable>
class __gc_vector;
template<typename T, typename Allocator, typename Lockable>
class __gc_deque;
template<typename T, typename Allocator, typename Lockable>
class __gc_forward_list;
template<typename T, typename Allocator, typename Lockable>
class __gc_list;
template<typename Key, typename Compare, typename Allocator, typename Lockable>
class __gc_set;
template<typename Key, typename Compare, typename Allocator, typename Lockable>
class __gc_multiset;
template<typename Key, typename T, typename Compare, typename Allocator, typename Lockable>
class __gc_map;
template<typename Key, typename T, typename Compare, typename Allocator, typename Lockable>
class __gc_multimap;
template<typename Key, typename Hash, typename KeyEqual, typename Allocator, typename Lockable>
class __gc_unordered_set;
template<typename Key, typename Hash, typename KeyEqual, typename Allocator, typename Lockable>
class __gc_unordered_multiset;
template<typename Key, typename T, typename Hash, typename KeyEqual, typename Allocator, typename Lockable>
class __gc_unordered_map;
template<typename Key, typename T, typename Hash, typename KeyEqual, typename Allocator, typename Lockable>
class __gc_unordered_multimap;
template<typename Lockable, typename ...Types>
class __gc_variant;
template<typename T, typename Lockable>
class __gc_optional;
// ------------------------ //
// -- garbage collection -- //
// ------------------------ //
class GC
{
public: // -- router function types -- //
struct router_fn;
struct mutable_router_fn;
private: // -- router function usage safety -- //
// gets if T is any of several types - equivalent to (std::is_same<T, Types>::value || ...) but doesn't require C++17 fold expressions
template<typename T, typename First, typename ...Rest>
struct is_same_any : std::integral_constant<bool, std::is_same<T, First>::value || GC::is_same_any<T, Rest...>::value> {};
template<typename T, typename First>
struct is_same_any<T, First> : std::integral_constant<bool, std::is_same<T, First>::value> {};
// defines if T is a router function object type - facilitates a type safety mechanism for GC::route().
template<typename T>
using is_router_function_object = GC::is_same_any<T, GC::router_fn, GC::mutable_router_fn>;
public: // -- router function definitions -- //
// THE FOLLOWING INFORMATION IS CRITICAL FOR ANY USAGE OF THIS LIBRARY.
// a type T is defined to be "gc" if it owns an object that is itself considered to be gc.
// by definition, GC::ptr, GC::atomic_ptr, and std::atomic<GC::ptr> are gc types.
// ownership means said "owned" object's lifetime is entirely controlled by the "owner".
// an object may only have one owner at any point in time - shared ownership is considered non-owning.
// thus global variables and static member variables are never considered to be owned objects.
// at any point in time, the owned object is considered to be part of its owner (i.e. as if it were a by-value member).
// the simplest form of ownership is a by-value member.
// another common category of owned object is a by-value container (e.g. the contents of std::vector, std::list, std::set, etc.).
// another case is a uniquely-owning pointer or reference - e.g. pointed-to object of std::unique_ptr, or any other (potentially-smart) pointer/reference to an object you know you own uniquely.
// of course, these cases can be mixed - e.g. a by-value member std::unique_ptr which is a uniquely-owning pointer to a by-value container std::vector of a gc type.
// it is important to remember that a container type like std::vector<T> is a gc type if T is a gc type (because it thus contains or "owns" gc objects).
// object reachability traversals are performed by router functions.
// for a gc type T, its router functions route a function-like object to its owned gc objects recursively.
// because object ownership cannot be cyclic, this will never degrade into infinite recursion.
// routing to anything you don't own is undefined behavior.
// routing to the same object twice is likewise undefined behavior.
// thus, although it is legal to route to the "contents" of an owned object (i.e. owned object of an owned object), it is typically dangerous to do so.
// in general, you should just route to all your by-value members - it is their responsibility to properly route the message the rest of the way.
// thus, if you own a std::vector<T> where T is a gc type, you should just route to the vector itself, which has its own router functions to route the message to its contents.
// if you are the owner of a gc type object, it is undefined behavior not to route to it (except in the special case of a mutable router function - see below).
// for a gc type T, a "mutable" owned object is defined to be an owned object for which you could legally route to its contents but said contents can be changed after construction.
// e.g. std::vector, std::list, std::set, and std::unique_ptr are all examples of "mutable" gc types because you own them (and their contents), but their contents can change.
// an "immutable" or "normal" owned object is defined as any owned object that is not "mutable".
// more formally, consider an owned object x:
// suppose you examine the set of all objects routed-to through x recursively.
// x is a "mutable" owned gc object iff for any two such router invocation sets taken over the lifetime of x the two sets are different.
// it should be noted that re-pointing a GC::ptr, GC::atomic_ptr, or std::atomic<GC::ptr> is not a mutating action for the purposes of classifying a "mutable" owned gc object.
// this is due to the fact that you would never route to its pointed-to contents due to it being a shared resource.
// the following is critical and easily forgotten:
// all mutating actions in a mutable gc object (e.g. adding items to a std::vector<GC::ptr<T>>) must occur in a manner mutually exclusive with the object's router function.
// this is because any thread may at any point make routing requests to any number of objects under gc management in any order and for any purpose.
// thus, if you have e.g. a std::vector<GC::ptr<T>>, you should also have a mutex to guard it on insertion/deletion/reordering of elements and for the router function.
// additionally, if your router function locks one or more mutexes, performing any actions that may self-route (e.g. a full garbage collection) will deadlock if any of the locks are still held.
// this can be fixed by either unlocking the mutex(es) prior to performing the self-routing action or by switching to a recursive mutex.
// this would likely need to be encapsulated by methods of your class to ensure external code can't violate this requirement (it is undefined behavior to violate this).
// on the bright side, cpp-gc has wrappers for all standard containers that internally apply all of this logic without the need to remember it.
// so, you could use a GC::vector<GC::ptr<T>> instead of a std::vector<GC::ptr<T>> and avoid the need to be careful or encapsulate anything.
// the following requirements pertain to router functions:
// for a normal router function (i.e. GC::router_fn) this must at least route to all owned gc objects.
// for a mutable router function (i.e. GC::mutable_router_fn) this must at least route to all owned "mutable" gc objects.
// the mutable router function system is entirely a method for optimization and can safely be ignored if desired.
// the following struct represents the router function set for objects of type T.
// the T in router<T> must not be cv-qualified.
// router functions must be static, named "route", return void, and take two args: a reference to (possibly cv-qualified) T and a by-value router function object (i.e. GC::router_fn or GC::mutable_router_fn).
// if you don't care about the efficiency mechanism of mutable router functions, you can define the function type as a template type paramter, but it must be deducible.
// the default implementation is no-op, which is suitable for any non-gc type.
// this should not be used directly for routing to owned objects - use the helper function GC::route() and GC::route_range() instead.
template<typename T>
struct router
{
// make sure we don't accidentally select a cv/ref-qualified default implementation
static_assert(std::is_same<T, std::remove_cv_t<std::remove_reference_t<T>>>::value, "router type T must not be cv/ref-qualified");
// defining this as true in any router<T> specialization marks it as trivial (more efficient algorithms).
// this is only safe iff ALL router functions in said specialization are no-op.
// otherwise it should be declared false or not declared at all (if not present, false is assumed).
// if set to true the router function(s) are ignored entirely (in fact, in this case they don't even need to exist).
static constexpr bool is_trivial = true;
};
public: // -- router intrinsics -- //
// get's if T's router is defined as trivial (i.e. this is true iff T is not a gc type).
// if T's router defines is_trivial to true, this value is true.
// if T's router defines is_trivial to false or does not define it at all, this value is false.
template<typename T>
struct has_trivial_router
{
private: // -- helpers -- //
// given a router type, creates an overload set that, when passed nullptr, resolves to a single function.
// said function's return type denotes the proper value.
template<typename R>
static std::false_type __returns_router_is_trivial(void*);
template<typename R, std::enable_if_t<R::is_trivial, int> = 0>
static std::true_type __returns_router_is_trivial(std::nullptr_t);
public: // -- public stuff -- //
static constexpr bool value = decltype(__returns_router_is_trivial<router<std::remove_cv_t<std::remove_reference_t<T>>>>(nullptr))::value;
};
// gets if all Types... are defined as trivial (i.e. this is true iff all the types are non-gc types).
// if no types are given, the value is true (i.e. nothing is trivial).
// equivalent to the C++17 fold expression (has_trivial_router<Types>::value && ...).
template<typename ...Types>
struct all_have_trivial_routers : std::true_type {};
template<typename T1, typename ...TN>
struct all_have_trivial_routers<T1, TN...> : std::integral_constant<bool, has_trivial_router<T1>::value && all_have_trivial_routers<TN...>::value> {};
public: // -- user-level routing utilities -- //
// recursively routes to obj - should only be used inside router functions
template<typename T, typename F, std::enable_if_t<!has_trivial_router<T>::value && is_router_function_object<F>::value, int> = 0>
static void route(const T &obj, F func)
{
// call the underlying router function - only required to be defined for non-trivial routers
GC::router<std::remove_cv_t<T>>::route(obj, func);
}
template<typename T, typename F, std::enable_if_t<has_trivial_router<T>::value && is_router_function_object<F>::value, int> = 0>
static void route(const T &obj, F func) {}
// recursively routes to each object in an iteration range - should only be used inside router functions
template<typename IterBegin, typename IterEnd, typename F, std::enable_if_t<!has_trivial_router<typename std::iterator_traits<IterBegin>::value_type>::value && is_router_function_object<F>::value, int> = 0>
static void route_range(IterBegin begin, IterEnd end, F func)
{
for (; begin != end; ++begin) GC::route(*begin, func);
}
template<typename IterBegin, typename IterEnd, typename F, std::enable_if_t<has_trivial_router<typename std::iterator_traits<IterBegin>::value_type>::value && is_router_function_object<F>::value, int> = 0>
static void route_range(IterBegin begin, IterEnd end, F func) {}
public: // -- exception types -- //
// exception type thrown by operations that violate testable disjunction rules.
// DISJUNCTION_SAFETY_CHECKS must be enabled for these to be checked.
class disjunction_error : public std::runtime_error
{
using std::runtime_error::runtime_error;
};
private: // -- private types -- //
struct info;
class disjoint_module;
// the virtual function table type for info objects.
struct info_vtable
{
void(*const destroy)(info&); // a function to destroy the object - allowed to deallocate obj's memory but must not deallocate the info object's memory.
void(*const dealloc)(info&); // a function to deallocate memory - called after destroy - must not call anything but deallocation functions (e.g. no destructors).
void(*const route)(info&, router_fn); // a router function to use for this object
void(*const mutable_route)(info&, mutable_router_fn); // a mutable router function to use for this object
info_vtable(void(*_destroy)(info&), void(*_dealloc)(info&), void(*_route)(info&, router_fn), void(*_mutable_route)(info&, mutable_router_fn))
: destroy(_destroy), dealloc(_dealloc), route(_route), mutable_route(_mutable_route)
{}
};
// represents a single garbage-collected object's allocation info.
// this is used internally by the garbage collector's logic - DO NOT MANUALLY MODIFY THIS.
// ANY POINTER OF THIS TYPE UNDER GC CONTROL MUST AT ALL TIMES POINT TO A VALID OBJECT OR NULL.
struct info
{
public: // -- core info -- //
void *const obj; // pointer to the managed object
const std::size_t count; // the number of elements in obj (meaning varies by implementer)
const info_vtable *const vtable; // virtual function table to use
// the disjunction this handle was constructed in.
// this must be used for disjoint utility functions.
// also used for applying disjunction safety checks.
disjoint_module *const disjunction;
// populates info - ref count starts at 1 - prev/next are undefined
info(void *_obj, std::size_t _count, const info_vtable *_vtable)
: obj(_obj), count(_count), vtable(_vtable), disjunction(disjoint_module::local())
{}
public: // -- vtable helpers -- //
void destroy() { vtable->destroy(*this); }
void dealloc() { vtable->dealloc(*this); }
void route(router_fn func) { vtable->route(*this, func); }
void mutable_route(mutable_router_fn func) { vtable->mutable_route(*this, func); }
public: // -- special resources -- //
// reference count - should only be used by disjoint module function under internal_mutex lock
std::size_t ref_count;
// mark flag - should only be used by the collector
bool marked;
// dlist pointers - should only be modified by obj_list methods.
// dlists have no other internal synchronization, so external code must make this thread safe if needed.
info *prev, *next;
public: // -- traversal utilities -- //
// marks this object and traverses to all routable targets for recursive marking.
// objects that have already been marked are skipped, so this is worst case O(n) in the number of existing objects.
void mark_sweep();
};
// used to select constructor paths that bind a new object
static struct bind_new_obj_t {} bind_new_obj;
// represents a raw_handle_t value with encapsulated syncronization logic.
// you should not use raw_handle_t directly - use this instead.
// NOT THREADSAFE - read/write from several threads on an instance of this object is undefined behavior.
class smart_handle
{
private: // -- data -- //
// the raw handle to manage.
// after construction, this must never be modified directly.
// all modification actions should be delegated to one of the collection_synchronizer functions.
info *raw;
// the disjunction this handle was constructed in.
// this is the disjunction that must be used by disjoint utility functions (all wrapped inside this class).
// also used for applying disjunction safety checks (if enabled).
disjoint_module *const disjunction;
friend class GC;
private: // -- private interface -- //
// initializes the info handle with the specified value and marks it as a root.
// the init object is added to the objects database in the same atomic step as the handle initialization.
// init must be the correct value of a current object - thus the return value of raw_handle() cannot be used.
// if DISJUNCTION_SAFETY_CHECKS are enabled, throws GC::disjunction_error if the object is in a different disjunction.
smart_handle(info *init, bind_new_obj_t) : disjunction(disjoint_module::local())
{
disjunction->schedule_handle_create_bind_new_obj(*this, init);
}
public: // -- ctor / dtor / asgn -- //
// initializes the info handle to null and marks it as a root.
smart_handle(std::nullptr_t = nullptr) : disjunction(disjoint_module::local())
{
disjunction->schedule_handle_create_null(*this);
}
// constructs a new smart handle to alias another.
// if DISJUNCTION_SAFETY_CHECKS are enabled, throws GC::disjunction_error if other's object is in a different disjunction.
smart_handle(const smart_handle &other) : disjunction(disjoint_module::local())
{
disjunction->schedule_handle_create_alias(*this, other);
}
// unroots the internal handle.
~smart_handle()
{
disjunction->schedule_handle_destroy(*this);
}
// safely repoints this smart_handle to other - equivalent to this->reset(other).
// if DISJUNCTION_SAFETY_CHECKS are enabled, throws GC::disjunction_error if other's object is in a different disjunction.
smart_handle &operator=(const smart_handle &other) { reset(other); return *this; }
public: // -- interface -- //
// gets the raw handle - guaranteed to outlive the object during a gc cycle.
// the value of the referenced pointer does not reflect the true current value.
// said value is only meant as a snapshot of the gc graph structure at an instance for the garbage collector.
// thus, using the value of the info* (and not just the pointer to the pointer) is undefined behavior.
// therefore this should never be used to get an argument for a smart_handle constructor.
info *const &raw_handle() const noexcept { return raw; }
// safely repoints the underlying raw handle at the new handle's object.
// if DISJUNCTION_SAFETY_CHECKS are enabled, throws GC::disjunction_error if the new handle's object is in a different disjunction.
void reset(const smart_handle &new_value)
{
disjunction->schedule_handle_repoint(*this, new_value);
}
// safely repoints the underlying raw handle at no object (null).
void reset()
{
disjunction->schedule_handle_repoint_null(*this);
}
// safely swaps the underlying raw handles.
void swap(smart_handle &other)
{
disjunction->schedule_handle_repoint_swap(*this, other);
}
friend void swap(smart_handle &a, smart_handle &b) { a.swap(b); }
};
private: // -- base router function -- //
// the base type for all router functions.
// this class should not be used directly.
// it is undefined behavior to delete this type polymorphically.
struct __base_router_fn
{
protected: // -- contents hidden for security -- //
void(*const func)(const smart_handle&); // raw function pointer to call
__base_router_fn(void(*_func)(const smart_handle&)) : func(_func) {}
__base_router_fn(std::nullptr_t) = delete;
~__base_router_fn() = default;
void operator()(const smart_handle &arg) { func(arg); }
void operator()(smart_handle&&) = delete; // for safety - ensures we can't call with an rvalue
};
public: // -- specific router function type definitions -- //
// type used for a normal router event
struct router_fn : __base_router_fn { using __base_router_fn::__base_router_fn; friend class GC; };
// type used for mutable router event
struct mutable_router_fn : __base_router_fn { using __base_router_fn::__base_router_fn; friend class GC; };
private: // -- extent extensions -- //
// gets the full (total) extent of a potentially multi-dimensional array.
// for scalar types this is 1.
// for array of unknown bound, returns the full extent of the known bounds.
template<typename T>
struct full_extent : std::integral_constant<std::size_t, 1> {};
template<typename T, std::size_t N>
struct full_extent<T[N]> : std::integral_constant<std::size_t, N * full_extent<T>::value> {};
template<typename T>
struct full_extent<T[]> : std::integral_constant<std::size_t, full_extent<T>::value> {};
public: // -- array typing helpers -- //
// true if T is an array of unknown bound, false otherwise
template<typename T>
struct is_unbound_array : std::false_type {};
template<typename T>
struct is_unbound_array<T[]> : std::true_type {};
// true if T is an array of known bound, false otherwise
template<typename T>
struct is_bound_array : std::false_type {};
template<typename T, std::size_t N>
struct is_bound_array<T[N]> : std::true_type {};
// stips off the top level of unbound array (bound is not stripped)
template<typename T>
struct remove_unbound_extent { typedef T type; };
template<typename T>
struct remove_unbound_extent<T[]> { typedef T type; };
// strips off the top level of bound array (unbound is not stripped)
template<typename T>
struct remove_bound_extent { typedef T type; };
template<typename T, std::size_t N>
struct remove_bound_extent<T[N]> { typedef T type; };
template<typename T> using remove_unbound_extent_t = typename remove_unbound_extent<T>::type;
template<typename T> using remove_bound_extent_t = typename remove_bound_extent<T>::type;
public: // -- cv type helping -- //
// a type representing if T is not cv qualified
template<typename T>
using no_cv = std::is_same<T, std::remove_cv_t<T>>;
// copies the cv qualifiers from From and applies them to To.
// if To is initially cv-qualified, those qualifiers are dropped prior to performing the cv copying process.
template<typename From, typename To>
struct copy_cv
{
private: // -- helpers -- //
typedef std::remove_cv_t<To> Dest;
typedef std::conditional_t<std::is_const<From>::value, const Dest, Dest> C_Dest;
typedef std::conditional_t<std::is_volatile<From>::value, volatile C_Dest, C_Dest> CV_Dest;
public: // -- interface -- //
typedef CV_Dest type;
};
template<typename From, typename To>
using copy_cv_t = typename copy_cv<From, To>::type;
// given a type T, aliases type T directly - used for e.g. preserving cv qualifiers during sfinae decltype deduction
template<typename T> struct type_alias { typedef T type; };
public: // -- ptr -- //
// a self-managed garbage-collected pointer to type T.
// if T is an unbound array, it is considered the "array" form, otherwise it is the "scalar" form.
// scalar and array forms may offer different interfaces.
// NOT THREADSAFE - this type is NOT internally synchronized.
// thus read/writes from several threads to the same ptr are undefined behavior (see atomic_ptr).
template<typename T>
struct ptr
{
public: // -- types -- //
// type of element stored
typedef GC::remove_unbound_extent_t<T> element_type;
private: // -- data -- //
// pointer to the object - this is only used for object access and is entirely unimportant as far a gc is concerned
element_type *obj;
// the raw handle wrapper - this is where all the important gc logic takes place
smart_handle handle;
// IMPORTANT: at all times during a ptr instance's lifetime: obj == null <=> handle == null
// however, handle cannot be checked for null (in a fast manner due to atomicity).
// violation of this constraint is undefined behavior.
// therefore, context must be used to guarantee this.
// e.g. constructing a new ptr can test this by testing the info* object passed to the obj insertion function for the gc database.
// e.g. a pre-existing ptr will be assumed to satisfy this.
friend class GC;
private: // -- helpers -- //
// changes what handle we should use, properly unlinking ourselves from the old one and linking to the new one.
// the new handle must come from a pre-existing ptr object.
// new_obj must be properly-sourced from new_handle->obj and non-null if new_handle is non-null.
// if new_handle (and new_obj) is null, the resulting state is empty.
// if DISJUNCTION_SAFETY_CHECKS are enabled, throws GC::disjunction_error if the new handle's object is in a different disjunction.
void reset(element_type *new_obj, const smart_handle &new_handle)
{
obj = new_obj;
handle.reset(new_handle);
}
// as reset(nullptr, nullptr) but avoids the intermediate conversion from nullptr to smart_handle
void reset()
{
obj = nullptr;
handle.reset();
}
// constructs a new ptr instance with the specified obj and pre-existing handle.
// this is equivalent to reset() but done at construction time for efficiency.
// if DISJUNCTION_SAFETY_CHECKS are enabled, throws GC::disjunction_error if the new handle's object is in a different disjunction.
ptr(element_type *new_obj, const smart_handle &new_handle) : obj(new_obj), handle(new_handle) {}
// constructs a new ptr instance with the specified obj and handle.
// for obj and handle: both must either be null or non-null - mixing null/non-null is undefined behavior.
// new_handle is automatically added to the gc database.
// new_handle must NOT have been sourced via handle.raw_handle().
// if DISJUNCTION_SAFETY_CHECKS are enabled, throws GC::disjunction_error if the objects is in a different disjunction.
ptr(element_type *new_obj, info *new_handle, bind_new_obj_t) : obj(new_obj), handle(new_handle, GC::bind_new_obj) {}
public: // -- ctor / dtor / asgn -- //
// creates an empty ptr (null)
ptr(std::nullptr_t = nullptr) : obj(nullptr), handle(nullptr) {}
~ptr()
{
#if DRAGAZO_GARBAGE_COLLECT_DEBUGGING_FEATURES
// set obj to null (better to get nullptr exceptions than segfaults)
// doing/not doing this doesn't matter for the obj/handle nullity assertion because we've ended the ptr's lifetime.
obj = nullptr;
#endif
}
// constructs a new gc pointer from a pre-existing one. allows any conversion that can be statically-checked.
// if DISJUNCTION_SAFETY_CHECKS are enabled, throws GC::disjunction_error if other's object is in a different disjunction.
ptr(const ptr &other) : obj(other.obj), handle(other.handle)
{}
template<typename J, std::enable_if_t<std::is_convertible<J*, T*>::value, int> = 0>
ptr(const ptr<J> &other) : obj(static_cast<element_type*>(other.obj)), handle(other.handle)
{}
// assigns a pre-existing gc pointer a new object. allows any conversion that can be statically-checked.
// if DISJUNCTION_SAFETY_CHECKS are enabled, throws GC::disjunction_error if other's object is in a different disjunction.
ptr &operator=(const ptr &other)
{
reset(other.obj, other.handle);
return *this;
}
template<typename J, std::enable_if_t<std::is_convertible<J*, T*>::value, int> = 0>
ptr &operator=(const ptr<J> &other)
{
reset(static_cast<element_type*>(other.obj), other.handle);
return *this;
}
// points this ptr at nothing (null) and severs ownership of the current object (if any).
ptr &operator=(std::nullptr_t) { reset(); return *this; }
public: // -- obj access -- //
// gets a pointer to the managed object. if this ptr does not point at a managed object, returns null.
// note that the returned pointer may become invalid if this ptr is reassigned or destroyed.
element_type *get() const noexcept { return obj; }
template<typename J = T, std::enable_if_t<std::is_same<T, J>::value && !std::is_same<J, void>::value, int> = 0>
auto &operator*() const& { return *get(); }
void operator*() && = delete; // for safety reasons, we don't allow dereferencing an rvalue ptr
element_type *operator->() const& noexcept { return get(); }
void operator->() && = delete; // for safety reasons, we don't allow dereferencing an rvalue ptr
// returns true iff this ptr points to a managed object (non-null)
explicit operator bool() const noexcept { return get() != nullptr; }
public: // -- array obj access -- //
// accesses an item in an array. only defined if T is an array type.
// undefined behavior if index is out of bounds.
template<typename J = T, std::enable_if_t<std::is_same<T, J>::value && GC::is_unbound_array<J>::value && !std::is_same<J, void>::value, int> = 0>
auto &operator[](std::ptrdiff_t index) const& { return get()[index]; }
void operator[](std::ptrdiff_t) && = delete; // for safety reasons, we don't allow dereferencing an rvalue ptr
// returns a ptr to the element with the specified index (no bounds checking).
// said ptr aliases the entire array - the array will not be deleted while the alias is still reachable.
// if this pointer does not refer to an object, the returned ptr is null and does not alias anything.
// exactly equivalent to GC::alias(p.get() + index, p).
template<typename J = T, std::enable_if_t<std::is_same<T, J>::value && GC::is_unbound_array<J>::value, int> = 0>
[[nodiscard]]
ptr<element_type> alias(std::ptrdiff_t index) const { return GC::alias(get() + index, *this); }
public: // -- comparison -- //
friend bool operator==(const ptr &a, const ptr &b) noexcept { return a.get() == b.get(); }
friend bool operator!=(const ptr &a, const ptr &b) noexcept { return a.get() != b.get(); }
friend bool operator<(const ptr &a, const ptr &b) noexcept { return a.get() < b.get(); }
friend bool operator<=(const ptr &a, const ptr &b) noexcept { return a.get() <= b.get(); }
friend bool operator>(const ptr &a, const ptr &b) noexcept { return a.get() > b.get(); }
friend bool operator>=(const ptr &a, const ptr &b) noexcept { return a.get() >= b.get(); }
friend bool operator==(const ptr &a, const element_type *b) noexcept { return a.get() == b; }
friend bool operator!=(const ptr &a, const element_type *b) noexcept { return a.get() != b; }
friend bool operator<(const ptr &a, const element_type *b) noexcept { return a.get() < b; }
friend bool operator<=(const ptr &a, const element_type *b) noexcept { return a.get() <= b; }
friend bool operator>(const ptr &a, const element_type *b) noexcept { return a.get() > b; }
friend bool operator>=(const ptr &a, const element_type *b) noexcept { return a.get() >= b; }
friend bool operator==(const element_type *a, const ptr &b) noexcept { return a == b.get(); }
friend bool operator!=(const element_type *a, const ptr &b) noexcept { return a != b.get(); }
friend bool operator<(const element_type *a, const ptr &b) noexcept { return a < b.get(); }
friend bool operator<=(const element_type *a, const ptr &b) noexcept { return a <= b.get(); }
friend bool operator>(const element_type *a, const ptr &b) noexcept { return a > b.get(); }
friend bool operator>=(const element_type *a, const ptr &b) noexcept { return a >= b.get(); }
public: // -- swap -- //
// swaps this ptr and the other ptr without performing unnecessary atomic inc/dec operations for managing the reference counts.
// if DISJUNCTION_SAFETY_CHECKS are enabled, throws GC::disjunction_error if either raw repoint action would be a disjunction violation.
void swap(ptr &other)
{
using std::swap;
swap(obj, other.obj);
swap(handle, other.handle);
}
friend void swap(ptr &a, ptr &b) { a.swap(b); }
};
// defines an atomic gc ptr.
// as ptr, but read/writes are synchronized and thus thread safe.
template<typename T>
struct atomic_ptr
{
private: // -- data -- //
GC::ptr<T> value;
mutable std::mutex mutex;
friend struct GC::router<atomic_ptr<T>>;
public: // -- ctor / dtor / asgn -- //
atomic_ptr() = default;
~atomic_ptr() = default;
atomic_ptr(const atomic_ptr&) = delete;
atomic_ptr &operator=(const atomic_ptr&) = delete;
public: // -- store / load -- //
atomic_ptr(const GC::ptr<T> &desired) : value(desired) {}
atomic_ptr &operator=(const GC::ptr<T> &desired)
{
store(desired);
return *this;
}
void store(const GC::ptr<T> &desired)
{
std::lock_guard<std::mutex> lock(this->mutex);
value = desired;
}
GC::ptr<T> load() const
{
std::lock_guard<std::mutex> lock(this->mutex);
GC::ptr<T> ret = value;
return ret;
}
operator GC::ptr<T>() const
{
return load();
}
public: // -- exchange -- //
GC::ptr<T> exchange(const GC::ptr<T> &desired)
{
std::lock_guard<std::mutex> lock(this->mutex);
ptr<T> old = value;
value = desired;
return old;
}
// !! add compare exchange stuff !! //
public: // -- lock info -- //
static constexpr bool is_always_lock_free = false;
bool is_lock_free() const noexcept { return is_always_lock_free; }
public: // -- swap -- //
void swap(atomic_ptr &other)
{
if (this != &other)
{
std::scoped_lock locks(this->mutex, other.mutex);
value.swap(other.value);
}
}
friend void swap(atomic_ptr &a, atomic_ptr &b) { a.swap(b); }
};
public: // -- ptr casting -- //
template<typename To, typename From, std::enable_if_t<std::is_convertible<From, To>::value || std::is_same<std::remove_cv_t<To>, std::remove_cv_t<From>>::value, int> = 0>
[[nodiscard]]
static ptr<To> staticCast(const GC::ptr<From> &p)
{
return ptr<To>(static_cast<typename ptr<To>::element_type*>(p.obj), p.handle);
}
template<typename To, typename From, std::enable_if_t<std::is_polymorphic<From>::value && !std::is_array<To>::value, int> = 0>
[[nodiscard]]
static ptr<To> dynamicCast(const GC::ptr<From> &p)
{
auto obj = dynamic_cast<typename ptr<To>::element_type*>(p.obj);
return obj ? ptr<To>(obj, p.handle) : ptr<To>();
}
template<typename To, typename From, std::enable_if_t<std::is_same<std::remove_cv_t<To>, std::remove_cv_t<From>>::value, int> = 0>
[[nodiscard]]
static ptr<To> constCast(const GC::ptr<From> &p)
{
return ptr<To>(const_cast<typename ptr<To>::element_type*>(p.obj), p.handle);
}
template<typename To, typename From>
[[nodiscard]]
static ptr<To> reinterpretCast(const GC::ptr<From> &p)
{
return ptr<To>(reinterpret_cast<typename ptr<To>::element_type*>(p.obj), p.handle);
}
public: // -- core router specializations -- //
// base case for router - this one actually does something directly
template<typename T>
struct router<ptr<T>>
{
template<typename F> static void route(const ptr<T> &obj, F func) { func(obj.handle); }
};
// an appropriate specialization for atomic_ptr (does not use any calls to gc functions - see generic std::atomic<T> ill-formed construction)
template<typename T>
struct router<atomic_ptr<T>>
{
template<typename F> static void route(const atomic_ptr<T> &atomic, F func)
{
// we avoid calling any gc functions by not actually using the load function - we just use the object directly.
std::lock_guard<std::mutex> lock(atomic.mutex);
GC::route(atomic.value, func);
}
};
public: // -- C-style array router specializations -- //
// routes a message directed at a C-style bounded array to each element in said array
template<typename T, std::size_t N>
struct router<T[N]>
{
static constexpr bool is_trivial = has_trivial_router<T>::value;
template<typename F>
static void route(const T(&objs)[N], F func)
{
for (const T &i : objs) GC::route(i, func);
}
};
// ill-formed variant for unbounded arrays
template<typename T>
struct router<T[]>
{
// intentionally left blank - we don't know the extent, so we can't route to its contents
};
public: // -- stdlib misc router specializations -- //
template<typename T, std::size_t N>
struct router<std::array<T, N>>
{
static constexpr bool is_trivial = has_trivial_router<T>::value;
template<typename F>
static void route(const std::array<T, N> &arr, F func)
{
GC::route_range(arr.begin(), arr.end(), func);
}
};
template<typename T1, typename T2>
struct router<std::pair<T1, T2>>
{
static constexpr bool is_trivial = all_have_trivial_routers<T1, T2>::value;
template<typename F>
static void route(const std::pair<T1, T2> &pair, F func)
{
GC::route(pair.first, func);
GC::route(pair.second, func);
}
};
template<typename ...Types>
struct router<std::tuple<Types...>>
{
static constexpr bool is_trivial = all_have_trivial_routers<Types...>::value;
template<typename F>
struct helper
{
// routes to tuple with index I and recurses to I + 1.
// as I defaults to 0, route() will route to all tuple elements in order of increasing index.
template<std::size_t I = 0, std::enable_if_t<(I < sizeof...(Types)), int> = 0>
static void route(const std::tuple<Types...> &tuple, F func)
{
GC::route(std::get<I>(tuple), func);
route<I + 1>(tuple, func);
}
template<std::size_t I = 0, std::enable_if_t<(I >= sizeof...(Types)), int> = 0>
static void route(const std::tuple<Types...> &tuple, F func) {}
};
template<typename F>
static void route(const std::tuple<Types...> &tuple, F func)
{
helper<F>::route(tuple, func);
}
};
template<typename T>
struct router<std::atomic<T>>
{
// ill-formed - we would need to read the atomic's value and if the T in atomic<T> uses a gc function on fetch, we could deadlock.
// you can avoid this problem if you can avoid calling any gc functions, in which case feel free to make a valid specialization.
};
public: // -- stdlib container router specializations -- //
template<typename T, typename Deleter>
struct router<std::unique_ptr<T, Deleter>>
{
static constexpr bool is_trivial = has_trivial_router<T>::value;
template<typename F>
static void route(const std::unique_ptr<T, Deleter> &obj, F func)
{
if (obj) GC::route(*obj, func);
}
};
template<typename T, typename Allocator>
struct router<std::vector<T, Allocator>>
{
static constexpr bool is_trivial = has_trivial_router<T>::value;
template<typename F>
static void route(const std::vector<T, Allocator> &vec, F func)
{
GC::route_range(vec.begin(), vec.end(), func);
}
};
template<typename T, typename Allocator>
struct router<std::deque<T, Allocator>>
{
static constexpr bool is_trivial = has_trivial_router<T>::value;
template<typename F>
static void route(const std::deque<T, Allocator> &deque, F func)
{
GC::route_range(deque.begin(), deque.end(), func);
}
};
template<typename T, typename Allocator>
struct router<std::forward_list<T, Allocator>>
{
static constexpr bool is_trivial = has_trivial_router<T>::value;
template<typename F>
static void route(const std::forward_list<T, Allocator> &list, F func)
{
GC::route_range(list.begin(), list.end(), func);
}
};
template<typename T, typename Allocator>
struct router<std::list<T, Allocator>>
{
static constexpr bool is_trivial = has_trivial_router<T>::value;
template<typename F>
static void route(const std::list<T, Allocator> &list, F func)
{
GC::route_range(list.begin(), list.end(), func);
}
};
template<typename Key, typename Compare, typename Allocator>
struct router<std::set<Key, Compare, Allocator>>
{
static constexpr bool is_trivial = has_trivial_router<Key>::value;
template<typename F>
static void route(const std::set<Key, Compare, Allocator> &set, F func)
{
GC::route_range(set.begin(), set.end(), func);
}