forked from rsashka/memsafe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrusted-cpp.h
More file actions
1100 lines (872 loc) · 37.5 KB
/
trusted-cpp.h
File metadata and controls
1100 lines (872 loc) · 37.5 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
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
#pragma once
#ifndef INCLUDED_TRUSTED_H_
#define INCLUDED_TRUSTED_H_
#ifndef DOXYGEN_SHOULD_SKIP_THIS
#include <iostream>
#include <stdint.h>
#include <stdexcept>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <thread>
#include <set>
#include <format>
#endif
#ifdef BUILD_UNITTEST
// Removing all restrictions on access to protected and private fields for testing cases
#define SCOPE(scope) public
#else
#define SCOPE(scope) scope
#endif
/**
* @def SCOPE( scope )
*
* Removing all restrictions on access to protected and private fields for testing cases
*
*/
#define TRUST_KEYWORD_ATTRIBUTE trust
#define TRUST_KEYWORD_PROFILE "profile"
#define TRUST_KEYWORD_STATUS "status"
#define TRUST_KEYWORD_UNSAFE "unsafe"
#define TRUST_KEYWORD_PRINT_AST "print-ast"
#define TRUST_KEYWORD_PRINT_DUMP "print-dump"
#define TRUST_KEYWORD_START_DUMP "#trust-dump\n"
#define TRUST_KEYWORD_ENABLE "enable"
#define TRUST_KEYWORD_DISABLE "disable"
#define TRUST_KEYWORD_PUSH "push"
#define TRUST_KEYWORD_POP "pop"
// maximum diagnostic level of plugin message when error is detected in source code
#define TRUST_KEYWORD_LEVEL "level"
#define TRUST_KEYWORD_ERROR "error"
#define TRUST_KEYWORD_WARNING "warning"
#define TRUST_KEYWORD_NOTE "note"
#define TRUST_KEYWORD_REMARK "remark"
#define TRUST_KEYWORD_IGNORED "ignored"
#define TRUST_KEYWORD_AUTO_TYPE "auto-type"
#define TRUST_KEYWORD_SHARED_TYPE "shared-type"
#define TRUST_KEYWORD_INVALIDATE_FUNC "invalidate-func"
#define TRUST_KEYWORD_USING_EXTERNAL "using-globals"
#define TRUST_KEYWORD_PURE "pure"
#define TRUST_KEYWORD_NOMINAL "nominal"
#define TRUST_KEYWORD_THREAD "thread"
#define TRUST_KEYWORD_THREADSAFE "threadsafe"
#define TRUST_KEYWORD_SET_ATTR_ARGS "set-attr-args"
#if defined __has_attribute
#if __has_attribute( TRUST_KEYWORD_ATTRIBUTE )
#define TRUSTED_ATTR(...) [[ TRUST_KEYWORD_ATTRIBUTE (__VA_ARGS__)]]
#define TRUSTED_BASELINE(number) TRUSTED_ATTR( TRUST_KEYWORD_BASELINE, #number) void trust_stub();
#endif
#endif
// Disable memory safety plugin attributes
#ifndef TRUSTED_ATTR
#define TRUSTED_ATTR(...)
#define TRUSTED_BASELINE(number)
#define TRUSTED_DISABLE
#endif
#ifndef TO_STR
#define TO_STR2(ARG) #ARG
#define TO_STR(ARG) TO_STR2(ARG)
#endif
#define TRUSTED_PROFILE(file) TRUSTED_ATTR(TRUST_KEYWORD_PROFILE, file)
#define TRUSTED_STATUS(status) TRUSTED_ATTR(TRUST_KEYWORD_STATUS, status)
#define TRUSTED_DIAG_LEVEL(level) TRUSTED_ATTR(TRUST_KEYWORD_LEVEL, level)
#define TRUSTED TRUSTED_ATTR(TRUST_KEYWORD_UNSAFE, TO_STR(__LINE__))
#define UNTRUSTED TRUSTED_ATTR(TRUST_KEYWORD_UNSAFE, TO_STR(__LINE__))
#define TRUSTED_ERROR_TYPE(name) TRUSTED_ATTR(TRUST_KEYWORD_ERROR "-type", name)
#define TRUSTED_WARNING_TYPE(name) TRUSTED_ATTR(TRUST_KEYWORD_WARNING "-type", name)
#define TRUSTED_AUTO_TYPE(name) TRUSTED_ATTR(TRUST_KEYWORD_AUTO_TYPE, name)
#define TRUSTED_SHARED_TYPE(name) TRUSTED_ATTR(TRUST_KEYWORD_SHARED_TYPE, name)
#define TRUSTED_INVALIDATE_FUNC(name) TRUSTED_ATTR(TRUST_KEYWORD_INVALIDATE_FUNC, name)
#define TRUSTED_PRINT_AST(filter) TRUSTED_ATTR(TRUST_KEYWORD_PRINT_AST, filter) void trust_stub();
#define TRUSTED_PRINT_DUMP(filter) TRUSTED_ATTR(TRUST_KEYWORD_PRINT_DUMP, filter) void trust_stub();
#define TRUST_USING_EXTERNAL(list) TRUSTED_ATTR(TRUST_KEYWORD_USING_EXTERNAL, list)
#define TRUST_PURE TRUSTED_ATTR(TRUST_KEYWORD_PURE)
#define TRUST_NOMINAL TRUSTED_ATTR(TRUST_KEYWORD_NOMINAL)
#define TRUST_NOMINAL_TYPES(list) TRUSTED_ATTR(TRUST_KEYWORD_NOMINAL, list)
#define TRUST_THREAD TRUSTED_ATTR(TRUST_KEYWORD_THREAD)
// Нельзя использовать атрубут thread списком, так как для этого требуется анализ тела функции
//#define TRUST_THREAD_TYPES(list) TRUSTED_ATTR(TRUST_KEYWORD_THREAD, list)
#define TRUST_THREADSAFE TRUSTED_ATTR(TRUST_KEYWORD_THREAD_SAFE)
#define TRUST_THREADSAFE_TYPES(list) TRUSTED_ATTR(TRUST_KEYWORD_THREADSAFE, list)
#define TRUST_SET_ATTR_ARGS(...) TRUSTED_ATTR(TRUST_KEYWORD_SET_ATTR_ARGS, __VA_ARGS__)
/**
* @def TRUSTED_ATTR(...)
*
* Inserts [[trust( ... )]] attributes into the С++ code
* if they are supported by the compiler
* and the library semantic analysis plugin is connected
*
*/
/**
* @def TRUSTED_PRINT_AST(...)
*
* Enables or disables the output of expressions from the source file as AST nodes.
* Expression filter is planned (not implemented yet).
*
* Control over AST dump output is implemented as a set of custom attributes
* in the stub function `void trust_stub()` forward declaration, as this can be done anywhere in C++ code.
*/
/**
* @def TRUSTED_PRINT_DUMP(...)
*
* Outputs the current state of the plugin and its main internal variables,
* as well as a stack of code blocks (hierarchies of variable lifetimes)
* for debugging and analysis.
*
*/
/**
* @def TRUSTED_DISABLE
*
* Defining a macro to disable the code analyzer plugin
* (this header file is compiled as normal C++ code without additional analysis by the compiler plugin)
*/
/**
* @def TRUSTED_PROFILE("file_name_profile")
*
* Select safety profile *(load from file not implemented)*.
* Empty mane - reset to default profile.
*/
/**
* @def TRUSTED_ERROR_TYPE("full:class::name")
*
* The fully qualified name of the class that will generate the error message
* when used (or when using a class derived from the specified one).
*/
/**
* @def TRUSTED_WARNING_TYPE("full:class::name")
*
* The fully qualified name of the class that will generate the warning message
* when used (or when using a class derived from the specified one).
*/
/**
* @def TRUSTED_SHARED_TYPE("full:class::name")
*
* The fully qualified name of a class that contains a strong pointer
* to shared data whose ownership is to be controlled at the syntax level.
*/
/**
* @def TRUSTED_AUTO_TYPE("full:class::name")
*
* The fully qualified name of a class that contains a strong pointer
* to an automatic (temporary) variable whose ownership must be controlled at the syntax level.
*/
/**
* @def TRUSTED_INVALIDATE_FUNC("unsafe function name")
* The name of a function that, when passed as an argument to a base object,
* always causes previously obtained references and iterators to be invalidated,
* regardless of the default settings @ref TRUSTED_NONCONST_ARG
* such as std::swap, std::move etc.
*/
namespace trust { // Begin define memory safety classes
#ifndef DOXYGEN_SHOULD_SKIP_THIS
class trust_error : public std::runtime_error {
public:
trust_error(std::string_view msg) : std::runtime_error(msg.begin()) {
}
};
#endif
// Pre-definition of template class for variable with weak reference
template <typename T> class Weak;
/*
* Base class for shared data with the ability to multi-thread synchronize access
*/
typedef std::chrono::milliseconds SyncTimeoutType;
static constexpr SyncTimeoutType SyncTimeoutDeedlock = std::chrono::milliseconds(5000);
template <typename V>
class Sync {
public:
V data;
Sync(V v) : data(v), m_const_lock(false) {
}
[[nodiscard]]
bool TryLock(bool const_lock, const SyncTimeoutType &timeout = SyncTimeoutDeedlock) {
m_const_lock = const_lock;
return m_const_lock ? try_lock_const(timeout) : try_lock(timeout);
}
void UnLock() {
if (m_const_lock) {
unlock_const();
} else {
unlock();
}
}
protected:
bool m_const_lock;
static void timeout_set_error(const SyncTimeoutType &timeout) {
if (timeout != SyncTimeoutDeedlock) {
throw trust_error("Timeout is not applicable for this object type!");
}
}
[[nodiscard]]
virtual bool try_lock(const SyncTimeoutType &timeout = SyncTimeoutDeedlock) {
timeout_set_error(timeout);
return true;
}
[[nodiscard]]
virtual bool try_lock_const(const SyncTimeoutType &timeout = SyncTimeoutDeedlock) {
timeout_set_error(timeout);
return true;
}
virtual void unlock() {
}
virtual void unlock_const() {
}
};
/**
* Temporary (auto) variable - owner of object reference (dereferences weak pointers
* and increments ownership count of strong references).
*
* Always contains only valid data (a valid reference and a captured synchronization object),
* otherwise an exception will be thrown when attempting to create the object.
*
* A helper template class wrapper for managing the lifetime
* of captured variables and releasing their ownership in the destructor.
* Similar to class and performs same functions as https://en.cppreference.com/w/cpp/thread/lock_guard
*
* V - Variable value type
* T - The type of the specific captured variable
*/
template <typename V, typename T>
class Locker {
public:
Locker(T val) : value(val) {
}
inline V& operator*() {
if constexpr (std::is_reference_v<T>) {
return value;
} else {
static_assert(std::is_convertible_v<T, std::shared_ptr<Sync < V>>>);
return value->data;
}
}
inline const V& operator*() const {
if constexpr (std::is_reference_v<T>) {
return value;
} else {
static_assert(std::is_convertible_v<T, std::shared_ptr<Sync < V>>>);
return value->data;
}
}
inline ~Locker() {
if constexpr (std::is_convertible_v<T, std::shared_ptr<Sync < V>>>) {
value->UnLock();
} else {
static_assert(std::is_reference_v<T>);
}
}
private:
T value; // Type T can be a reference to data i.e. V& or a shared_ptr<Sync<V>>
// Noncopyable
Locker(const Locker&) = delete;
Locker& operator=(const Locker&) = delete;
// Nonmovable
Locker(Locker&&) = delete;
Locker& operator=(Locker&&) = delete;
};
/**
* Variable by value without references.
* A simple wrapper over data to unify access to it using class Auto
*/
template <typename V>
class Value {
protected:
V value;
public:
Value(V val) : value(val) {
}
inline V& operator*() {
return value;
};
inline const V& operator*() const {
return value;
};
inline Locker<V, V&> lock() {
return Locker<V, V&> (value);
}
inline Locker<V, V&> lock() const {
return lock_const();
}
inline const Locker<V, V&> lock_const() const {
return Locker<V, V&> (value);
}
};
static_assert(std::is_standard_layout_v<Value<int>>);
/**
* Reference variable (shared pointer) with optional multi-threaded access control.
*
* By default using template @ref Sync without multithreaded access control.
* @see @ref SyncSingleThread, @ref SyncTimedMutex, @ref SyncTimedShared )
*
*/
template <typename V, template <typename> typename S = Sync>
class Shared : public std::shared_ptr< S<V> > {
public:
typedef V ValueType;
typedef S<V> DataType;
typedef std::weak_ptr<DataType> WeakType;
typedef std::shared_ptr<DataType> SharedType;
Shared() : SharedType(nullptr) {
}
Shared(const V & val) : SharedType(std::make_shared<DataType>(val)) {
}
Shared(Shared<V, S> &val) : SharedType(val) {
}
static Locker<V, SharedType> make_auto(SharedType * shared, bool read_only, const SyncTimeoutType &timeout = SyncTimeoutDeedlock) {
if constexpr (!std::is_same_v<Sync<V>, DataType>) { // The Sync class is virtual
if (!shared || !shared->get()) {
throw trust_error("Object missing (null pointer exception)");
}
if (!shared->get()->TryLock(read_only, timeout)) {
throw trust_error(std::format("try_lock{} timeout", read_only ? " read only" : ""));
}
}
return Locker<V, SharedType> (*shared);
}
Locker<V, SharedType> lock(const SyncTimeoutType &timeout = SyncTimeoutDeedlock) {
return make_auto(this, false, timeout);
}
Locker<V, SharedType> lock_const(const SyncTimeoutType &timeout = SyncTimeoutDeedlock) {
return make_auto(this, true, timeout);
}
// template < typename = std::enable_if<std::is_trivially_copyable_v < V >> >
inline V & operator*() const {
auto guard_lock = lock_const();
return *guard_lock;
}
// template < typename = std::enable_if<std::is_trivially_copyable_v < V >> >
inline SharedType & operator=(V && value) {
auto guard_lock = lock();
*guard_lock = value;
return *this;
}
inline SharedType & set(V && value, const SyncTimeoutType &timeout = SyncTimeoutDeedlock) {
auto guard_lock = lock(timeout);
*guard_lock = value;
return *this;
}
// template < typename = std::enable_if<std::is_trivially_copyable_v < V >> >
// inline SharedType & operator=(SharedType & s) {
// auto guard_lock = lock_const();
// return this->trust::shared_ptr<S < V>>::operator*().data;
// }
//
inline Weak<Shared < V, S >> weak() {
return Weak<Shared < V, S >> (*this);
}
inline explicit operator bool() const noexcept {
return this->get();
}
};
/**
* A wrapper template class for storing weak pointers to shared variables
*/
template <typename T>
class Weak : public T::WeakType {
public:
Weak() : T::WeakType(nullptr) {
}
Weak(const T ptr) : T::WeakType(ptr) {
}
Weak(Weak & old) : T::WeakType(old) {
}
Locker<typename T::ValueType, typename T::SharedType> make_auto(bool read_only, const SyncTimeoutType &timeout = SyncTimeoutDeedlock) {
typename T::SharedType shared = this->T::WeakType::lock();
return T::make_auto(&shared, read_only, timeout);
}
inline Locker<typename T::ValueType, typename T::SharedType> lock(const SyncTimeoutType &timeout = SyncTimeoutDeedlock) {
return make_auto(false, timeout);
}
inline const Locker<typename T::ValueType, T> lock_const(const SyncTimeoutType &timeout = SyncTimeoutDeedlock) const {
return make_auto(true, timeout);
}
// template < typename = std::enable_if<std::is_trivially_copyable_v < V >> >
inline T::ValueType & operator*() const {
auto guard_lock = lock_const();
return *guard_lock;
}
// template < typename = std::enable_if<std::is_trivially_copyable_v < V >> >
inline Weak<T> & operator=(T::ValueType && value) {
auto guard_lock = lock();
*guard_lock = value;
return *this;
}
inline Weak<T> & set(T::ValueType && value, const SyncTimeoutType &timeout = SyncTimeoutDeedlock) {
auto guard_lock = lock(timeout);
*guard_lock = value;
return *this;
}
inline explicit operator bool() const noexcept {
return this->lock();
}
};
/**
* A class without a synchronization primitive and with the ability to work only in one application thread.
* Used to control access to data from only one application thread without creating a synchronization object between threads.
*/
template <typename V>
class SyncSingleThread : public Sync<V> {
public:
SyncSingleThread(V v) : Sync<V>(v), m_thread_id(std::this_thread::get_id()) {
}
protected:
const std::thread::id m_thread_id;
inline void check_thread() {
if (m_thread_id != std::this_thread::get_id()) {
throw trust_error("Using a single thread variable in another thread!");
}
}
inline bool try_lock(const SyncTimeoutType &timeout) override final {
check_thread();
Sync<V>::timeout_set_error(timeout);
return true;
}
inline void unlock() override final {
check_thread();
}
inline bool try_lock_const(const SyncTimeoutType &timeout) override final {
check_thread();
Sync<V>::timeout_set_error(timeout);
return true;
}
inline void unlock_const() override final {
check_thread();
}
};
/**
* Class with timed mutex for simple multithreaded synchronization
*/
template <typename V>
class SyncTimedMutex : public Sync<V>, protected std::timed_mutex {
public:
SyncTimedMutex(V v) : Sync<V>(v) {
}
protected:
inline bool try_lock(const SyncTimeoutType &timeout) override final {
return std::timed_mutex::try_lock_for(timeout);
}
inline void unlock() override final {
std::timed_mutex::unlock();
}
inline bool try_lock_const(const SyncTimeoutType &timeout) override final {
return std::timed_mutex::try_lock_for(timeout);
}
inline void unlock_const() override final {
std::timed_mutex::unlock();
}
};
/**
* Class with shared_timed_mutex for multi-thread synchronization for exclusive read/write lock or shared read-only lock
*/
template <typename V>
class SyncTimedShared : public Sync<V>, protected std::shared_timed_mutex {
public:
SyncTimedShared<V>(V v) : Sync<V>(v) {
}
protected:
inline bool try_lock(const SyncTimeoutType &timeout) override final {
return std::shared_timed_mutex::try_lock_for(timeout);
}
inline void unlock() override final {
std::shared_timed_mutex::unlock();
}
inline bool try_lock_const(const SyncTimeoutType &timeout) override final {
return std::shared_timed_mutex::try_lock_shared_for(timeout);
}
inline void unlock_const() override final {
std::shared_timed_mutex::unlock_shared();
}
};
/**
* Class field reference variable (shared pointer) without multi-threaded access control
* to store an object of the same class with protection against recursive references at runtime.
*
* Should not be used at all, since the check is performed at runtime and
* its execution time depends on the total number of links being checked.
*
* When created, requires the address of the object and the address of the field
* in the object to calculate its position in the class field, which must be correct.
*
* To check std::is_standard_layout v the class cannot have virtual methods,
* including a destructor, be derived from another class and much more...
*
*/
template <typename V>
class [[deprecated]] Class {
public:
std::shared_ptr<V> m_field; ///< Field data with a pointer to an instance of the class containing this field (to another instance of the same class)
V * m_instance; ///< A pointer to the object instance that contains this field.
size_t m_offset; ///< Offset of this field from the pointer to the class instance
typedef std::weak_ptr<V> WeakType;
inline bool checkFieldPosInOwner(const V & owner, size_t offset) const {
return ((size_t) & owner + offset) == (size_t)this;
}
inline bool checkCircularReference(const V * owner, const V * tested) const {
if (!owner || !tested) {
return true;
} else if (owner == tested) {
return false;
}
const Class<V> * filed = reinterpret_cast<const Class<V> *> (reinterpret_cast<size_t> (owner) + m_offset);
return checkCircularReference(filed->m_field.get(), tested);
}
Class(V & owner, Class<V> &filed, V *ptr = nullptr) : m_field(std::shared_ptr<V>(ptr)), m_instance(&owner) {
m_offset = reinterpret_cast<size_t> (& filed) - reinterpret_cast<size_t> (& owner);
if (!checkCircularReference(m_instance, ptr)) {
throw trust_error("Circular reference exception");
}
assert(&owner != ptr);
assert(checkFieldPosInOwner(*m_instance, m_offset));
}
Class<V> & operator=(Class<V> & copy) {
// Check for a copy of another field in your own object
if (m_instance == copy.m_instance) {
throw trust_error("Copy of another field exception");
}
*this = copy.m_field.get(); // Call Class<V> & operator=(V *cls)
return *this;
}
Class<V> & operator=(V * cls) {
if (!checkCircularReference(m_instance, cls)) {
throw trust_error("Circular reference exception");
}
m_field = std::shared_ptr<V>(cls);
return *this;
}
inline V& operator*() {
if (V * temp = m_field.get()) {
return *temp;
}
throw trust_error("null pointer exception");
}
inline const V& operator*() const {
if (const V * temp = m_field.get()) {
return *temp;
}
throw trust_error("null pointer exception");
}
Weak<Class < V >> weak() {
return Weak<Class < V >> (*this, nullptr, nullptr);
}
};
#pragma clang attribute push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
static_assert(std::is_standard_layout_v<std::shared_ptr<int>>);
static_assert(std::is_standard_layout_v<Class<int>>);
#pragma clang attribute pop
/**
* An example of a linked list template implemented using weak pointers
* (where strong references between the same data types are not allowed).
*/
template <typename T>
struct LinkedWeakNode {
typedef std::weak_ptr<LinkedWeakNode<T>> WeakType;
WeakType next;
T data;
LinkedWeakNode(const T & value) : data(value) {
}
};
template <typename T>
class LinkedWeakList {
public:
typedef LinkedWeakNode<T> NodeType;
typedef std::shared_ptr<NodeType> SharedType;
SharedType m_head;
std::set<SharedType> m_data;
LinkedWeakList() : m_head(nullptr) {
}
// Function to Insert a new node at the beginning of the list
void push_front(T && data) {
SharedType node = std::make_shared<NodeType>(data);
m_data.insert(node);
node->next = m_head;
m_head = node;
}
void push_back(T && data) {
SharedType node = std::make_shared<NodeType>(data);
m_data.insert(node);
// If the linked list is empty, update the head to the new node
if (!m_head) {
m_head = node;
return;
}
// Traverse to the last node
SharedType temp = m_head;
while (temp->next.lock()) {
temp = temp->next.lock();
}
// Update the last node's next to the new node
temp->next = node;
}
// Function to Delete the first node of the list
void pop_front() {
if (!m_head) {
std::cerr << "List is empty." << std::endl;
return;
}
SharedType temp = m_head;
m_head = m_head->next.lock();
m_data.erase(temp);
}
// Function to Delete the last node of the list
void pop_back() {
if (!m_head) {
std::cerr << "List is empty." << std::endl;
return;
}
SharedType temp = m_head->next.lock();
if (!temp) {
m_data.erase(m_head);
m_head.reset();
return;
}
// Traverse to the second-to-last node
while (temp->next.lock()->next.lock()) {
temp = temp->next.lock();
}
// Delete the last node
m_data.erase(temp->next.lock());
}
size_t size() {
return m_data.size();
}
size_t empty() {
return m_data.empty();
}
std::string to_string() {
if (!m_head) {
return "nullptr";
}
std::string result;
SharedType temp = m_head;
while (temp) {
result += std::to_string(temp->data);
result += " -> ";
temp = temp->next.lock();
}
return result;
}
};
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/**
* Helper class for lazy invocation of iterator
*/
class LazyCallerInterface {
public:
auto operator*();
auto operator*() const;
};
//std::tuple_element_t<N, std::tuple<InputPortTypes...>>
// template <typename T, typename R, typename ... Args> class LazyCaller;
template<int...> struct index_tuple {
};
template<int I, typename IndexTuple, typename... Types>
struct make_indexes_impl;
template<int I, int... Indexes, typename T, typename ... Types>
struct make_indexes_impl<I, index_tuple<Indexes...>, T, Types...> {
typedef typename make_indexes_impl<I + 1, index_tuple<Indexes..., I>, Types...>::type type;
};
template<int I, int... Indexes>
struct make_indexes_impl<I, index_tuple<Indexes...> > {
typedef index_tuple<Indexes...> type;
};
template<typename ... Types>
struct make_indexes : make_indexes_impl<0, index_tuple<>, Types...> {
};
template<typename T, typename R, typename ... Args, int... Indexes >
R call_helper(T &obj, R(T::*method)(Args...), index_tuple< Indexes... >, std::tuple<Args...>&& tup) {
return (obj.*method)(std::forward<Args>(std::get<Indexes>(tup))...);
}
template<typename T, typename R, typename ... Args>
R call(T &obj, R(T::*method)(Args...), const std::tuple<Args...>& tup) {
return call_helper(obj, method, typename make_indexes<Args...>::type(), std::tuple<Args...>(tup));
}
template<typename T, typename R, typename ... Args>
R call(T &obj, R(T::*method)(Args...), std::tuple<Args...>&& tup) {
return call_helper(obj, method, typename make_indexes<Args...>::type(), std::forward<std::tuple<Args...>>(tup));
}
#ifdef _MSC_VER // Microsoft compilers
#define EXPAND(x) x
#define __NARGS(_1, _2, _3, _4, _5, _6, _7, _8, _9, VAL, ...) VAL
#define NARGS_1(...) EXPAND(__NARGS(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
#define AUGMENTER(...) unused, __VA_ARGS__
#define NARGS(...) NARGS_1(AUGMENTER(__VA_ARGS__))
#else // Others
#define NARGS(...) __NARGS(0, ## __VA_ARGS__, 9,8,7,6,5,4,3,2,1,0)
#define __NARGS(_0,_1,_2,_3,_4,_5,_6,_7,_8,_9,N,...) N
#endif
static_assert(NARGS() == 0);
static_assert(NARGS(A) == 1);
static_assert(NARGS(A, B) == 2);
static_assert(NARGS(A, B, C) == 3);
static_assert(NARGS(A, B, C, D) == 4);
static_assert(NARGS(A, B, C, D, E) == 5);
static_assert(NARGS(A, B, C, D, E, F) == 6);
static_assert(NARGS(A, B, C, D, E, F, G) == 7);
static_assert(NARGS(A, B, C, D, E, F, G, X) == 8);
static_assert(NARGS(A, B, C, D, E, F, G, X, Y) == 9);
// //decltype(std::declval<decltype(variable)>().method(__VA_ARGS__)) __VA_OPT__(,) DECLTYPE(__VA_ARGS__)
//
// template<typename T>
// struct arg_helper {
//
// static auto type_arg(T arg) {
// return arg;
// }
//
// static auto type_call(T arg) {
// if constexpr (std::is_class_v<T> && std::is_base_of_v<LazyCallerInterface, T>) {
// return arg;
// } else {
// return arg;
// }
// }
// };
//
//#define DECLTYPE_EXPAND_TYPE(arg) decltype(arg_helper<decltype(arg)>::type_call(arg))
// // std::conditional<(std::is_class_v<decltype(arg)> && std::is_base_of_v<LazyCallerInterface, decltype(arg)>), decltype(*arg), decltype(arg)>::type
// //decltype(arg)
// //std::conditional<!(std::is_class_v<decltype(arg)> && std::is_base_of_v<LazyCallerInterface, decltype(arg)>), decltype(arg), decltype(std::declval<decltype(arg)>().operator*())>::type
#define DECLTYPE_EXPAND_0()
#define DECLTYPE_EXPAND_1(arg1) decltype(arg1)
#define DECLTYPE_EXPAND_2(arg1, arg2) decltype(arg1), decltype(arg2)
#define DECLTYPE_EXPAND_3(arg1, arg2, arg3) decltype(arg1), decltype(arg2), decltype(arg3)
#define DECLTYPE_EXPAND_4(arg1, arg2, arg3, arg4) decltype(arg1), decltype(arg2), decltype(arg3), decltype(arg4)
#define DECLTYPE_EXPAND_5(arg1, arg2, arg3, arg4, arg5) decltype(arg1), decltype(arg2), decltype(arg3), decltype(arg4), decltype(arg5)
#define DECLTYPE_EXPAND_6(arg1, arg2, arg3, arg4, arg5, arg6) decltype(arg1), decltype(arg2), decltype(arg3), decltype(arg4), decltype(arg5), decltype(arg6)
#define DECLTYPE_EXPAND_7(arg1, arg2, arg3, arg4, arg5, arg6, arg7) decltype(arg1), decltype(arg2), decltype(arg3), decltype(arg4), decltype(arg5), decltype(arg6), decltype(arg7)
#define DECLTYPE_EXPAND_8(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) decltype(arg1), decltype(arg2), decltype(arg3), decltype(arg4), decltype(arg5), decltype(arg6), decltype(arg7), decltype(arg8)
#define DECLTYPE_EXPAND_9(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) decltype(arg1), decltype(arg2), decltype(arg3), decltype(arg4), decltype(arg5), decltype(arg6), decltype(arg7), decltype(arg8), decltype(arg9)
#define DECLTYPE_EXPAND_HELPER(count, ...) DECLTYPE_EXPAND_ ## count (__VA_ARGS__)
#define DECLTYPE_EXPAND(count, ...) DECLTYPE_EXPAND_HELPER(count, __VA_ARGS__)
#define DECLTYPE(...) DECLTYPE_EXPAND(NARGS(__VA_ARGS__) __VA_OPT__(,) __VA_ARGS__)
//
//#define DECLTYPE_ARG_TYPE(arg) decltype(arg_helper<decltype(arg)>::type_arg(arg))
//
//#define DECLTYPE_ARG_0()
//#define DECLTYPE_ARG_1(arg1) DECLTYPE_ARG_TYPE(arg1)
//#define DECLTYPE_ARG_2(arg1, arg2) DECLTYPE_ARG_TYPE(arg1), DECLTYPE_ARG_TYPE(arg2)
//#define DECLTYPE_ARG_3(arg1, arg2, arg3) DECLTYPE_ARG_TYPE(arg1), DECLTYPE_ARG_TYPE(arg2), DECLTYPE_ARG_TYPE(arg3)
//#define DECLTYPE_ARG_4(arg1, arg2, arg3, arg4) DECLTYPE_ARG_TYPE(arg1), DECLTYPE_ARG_TYPE(arg2), DECLTYPE_ARG_TYPE(arg3), DECLTYPE_ARG_TYPE(arg4)
//#define DECLTYPE_ARG_5(arg1, arg2, arg3, arg4, arg5) DECLTYPE_ARG_TYPE(arg1), DECLTYPE_ARG_TYPE(arg2), DECLTYPE_ARG_TYPE(arg3), DECLTYPE_ARG_TYPE(arg4), DECLTYPE_ARG_TYPE(arg5)
//#define DECLTYPE_ARG_6(arg1, arg2, arg3, arg4, arg5, arg6) DECLTYPE_ARG_TYPE(arg1), DECLTYPE_ARG_TYPE(arg2), DECLTYPE_ARG_TYPE(arg3), DECLTYPE_ARG_TYPE(arg4), DECLTYPE_ARG_TYPE(arg5), DECLTYPE_ARG_TYPE(arg6)
//#define DECLTYPE_ARG_7(arg1, arg2, arg3, arg4, arg5, arg6, arg7) DECLTYPE_ARG_TYPE(arg1), DECLTYPE_ARG_TYPE(arg2), DECLTYPE_ARG_TYPE(arg3), DECLTYPE_ARG_TYPE(arg4), DECLTYPE_ARG_TYPE(arg5), DECLTYPE_ARG_TYPE(arg6), DECLTYPE_ARG_TYPE(arg7)
//#define DECLTYPE_ARG_8(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) DECLTYPE_ARG_TYPE(arg1), DECLTYPE_ARG_TYPE(arg2), DECLTYPE_ARG_TYPE(arg3), DECLTYPE_ARG_TYPE(arg4), DECLTYPE_ARG_TYPE(arg5), DECLTYPE_ARG_TYPE(arg6), DECLTYPE_ARG_TYPE(arg7), DECLTYPE_ARG_TYPE(arg8)
//#define DECLTYPE_ARG_9(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) DECLTYPE_ARG_TYPE(arg1), DECLTYPE_ARG_TYPE(arg2), DECLTYPE_ARG_TYPE(arg3), DECLTYPE_ARG_TYPE(arg4), DECLTYPE_ARG_TYPE(arg5), DECLTYPE_ARG_TYPE(arg6), DECLTYPE_ARG_TYPE(arg7), DECLTYPE_ARG_TYPE(arg8), DECLTYPE_ARG_TYPE(arg9)
//
//#define DECLTYPE_ARG_HELPER(count, ...) DECLTYPE_ARG_ ## count (__VA_ARGS__)
//#define DECLTYPE_ARG(count, ...) DECLTYPE_ARG_HELPER(count, __VA_ARGS__)
//#define DECLTYPE_ARGS(...) DECLTYPE_ARG(NARGS(__VA_ARGS__) __VA_OPT__(,) __VA_ARGS__)
//
#endif
/**
* @def LAZYCALL(variable, method, ...)
*
* Macro for creating a deferred call to a class method.
* Used to safely work with data types listed using the macro.
*
* Method arguments cannot be of types from the list @ref TRUSTED_INVALIDATE
*
* Someday, using static reflection, the same thing can be done without macros.
*
*/
#define LAZYCALL(variable, method, ...) LazyCaller<decltype(variable), decltype(std::declval<decltype(variable)>().method(__VA_ARGS__)) __VA_OPT__(,) DECLTYPE(__VA_ARGS__) >(variable, &decltype(variable):: method __VA_OPT__(,) __VA_ARGS__ )
/**
* Lazy (deferred) invocation of class methods to safely work
* with iterators and other types of addresses
* that may become invalid after the underlying object's data has changed.
*
* @ref LAZYCALL()
*/
template <typename T, typename R, typename ... Args>
class LazyCaller : public LazyCallerInterface {
T &object;
union {
R(T::*method)(Args...);
R(T::*method_const)(Args...) const;
};
std::tuple<Args...> args;
public:
LazyCaller(T &var, R(T::*call)(Args...), Args&&... args) : object(var), method(call), args(std::make_tuple(std::forward<Args>(args)...)) {