StormByte 3.0.0
C++26 foundation of the StormByte suite
Loading...
Searching...
No Matches
pointers.txx
Go to the documentation of this file.
1/*
2 * Copyright (C) 2024-2026 David C. Manuelda (StormBytePP)
3 *
4 * This is the base for StormByte Suite libraries.
5 *
6 * StormByte original source is dual-licensed:
7 *
8 * 1. GNU Lesser General Public License v3.0 (or later)
9 * You may redistribute and/or modify this file under the terms of the
10 * GNU Lesser General Public License as published by the Free Software
11 * Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * 2. Commercial license
15 * Alternatively, this file may be used under the terms of a commercial
16 * license agreement with the copyright holder
17 * (David C. Manuelda <StormByte@gmail.com>).
18 *
19 * Both licenses apply only to original StormByte source in this repository.
20 * They do not cover other StormByte modules or any third-party material
21 * shipped with this repository (including everything under thirdparty/),
22 * which remains under its own license.
23 *
24 * Neither license grants any patent rights. Any patent licenses required
25 * to use this software or third-party components must be obtained separately
26 * from the patent holders.
27 *
28 * StormByte is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU Lesser General Public License for more details.
32 *
33 * You should have received a copy of the GNU Lesser General Public License
34 * version 3 along with StormByte. If not, see
35 * <https://www.gnu.org/licenses/lgpl-3.0.html>.
36 *
37 * SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-StormByte-Commercial
38 */
39
40#pragma once
41
42#include <atomic>
43#include <cstddef>
44#include <new>
45#include <type_traits>
46#include <utility>
47
48namespace StormByte {
49 namespace Safe {
50 namespace Detail {
51 /**
52 * @brief Allocate a control block and a @p T in one Base block.
53 * @tparam T Object type.
54 * @tparam Args Constructor argument types.
55 * @param args Arguments forwarded to @p T.
56 * @return Control block. The object address is @ref Control::Object.
57 * @throws AllocationError The block could not be allocated.
58 */
59 template<class T, class... Args>
60 Control* Create(Args&&... args) {
61 constexpr std::size_t align = alignof(T) > alignof(Control) ? alignof(T) : alignof(Control);
62 const std::size_t controlSize = (sizeof(Control) + align - 1) & ~(align - 1);
63 void* block = Heap::Allocate(controlSize + sizeof(T));
64 Control* control = static_cast<Control*>(block);
65 T* object = reinterpret_cast<T*>(static_cast<unsigned char*>(block) + controlSize);
66 control->Strong.store(1, std::memory_order_relaxed);
67 control->Weak.store(1, std::memory_order_relaxed);
68 control->Object = object;
69 control->Destroy = [](Control* dying) noexcept {
70 static_cast<T*>(dying->Object)->~T();
71 };
72 try {
73 new (object) T(std::forward<Args>(args)...);
74 } catch (...) {
75 Heap::Free(block);
76 throw;
77 }
78 return control;
79 }
80
81 /**
82 * @brief Drop one strong reference and destroy the object when it was the last.
83 * @param control Control block.
84 */
85 inline void ReleaseStrong(Control* control) noexcept {
86 if (control == nullptr)
87 return;
88 if (control->Strong.fetch_sub(1, std::memory_order_acq_rel) == 1) {
89 control->Destroy(control);
90 if (control->Weak.fetch_sub(1, std::memory_order_acq_rel) == 1)
91 Heap::Free(control);
92 }
93 }
94
95 /**
96 * @brief Drop one weak reference and free the block when it was the last.
97 * @param control Control block.
98 */
99 inline void ReleaseWeak(Control* control) noexcept {
100 if (control == nullptr)
101 return;
102 if (control->Weak.fetch_sub(1, std::memory_order_acq_rel) == 1)
103 Heap::Free(control);
104 }
105 }
106
107 template<class T>
108 Shared<T>::Shared() noexcept: m_control(nullptr), m_object(nullptr) {}
109
110 template<class T>
111 Shared<T>::Shared(std::nullptr_t) noexcept: m_control(nullptr), m_object(nullptr) {}
112
113 template<class T>
114 template<class U>
115 requires Type::ConvertibleTo<U*, T*>
116 Shared<T>::Shared(const Shared<U>& other) noexcept: m_control(other.m_control), m_object(other.m_object) {
117 if (m_control != nullptr)
118 m_control->Strong.fetch_add(1, std::memory_order_relaxed);
119 }
120
121 template<class T>
122 template<class U>
123 requires Type::ConvertibleTo<U*, T*>
124 Shared<T>::Shared(Shared<U>&& other) noexcept: m_control(other.m_control), m_object(other.m_object) {
125 other.m_control = nullptr;
126 other.m_object = nullptr;
127 }
128
129 template<class T>
130 Shared<T>::Shared(const Shared& other) noexcept: m_control(other.m_control), m_object(other.m_object) {
131 if (m_control != nullptr)
132 m_control->Strong.fetch_add(1, std::memory_order_relaxed);
133 }
134
135 template<class T>
136 Shared<T>::Shared(Shared&& other) noexcept: m_control(other.m_control), m_object(other.m_object) {
137 other.m_control = nullptr;
138 other.m_object = nullptr;
139 }
140
141 template<class T>
142 Shared<T>::Shared(const Weak<T>& weak): m_control(nullptr), m_object(nullptr) {
143 Shared locked = weak.lock();
144 if (!locked)
145 Heap::ThrowExpiredWeakPointer();
146 m_control = locked.m_control;
147 m_object = locked.m_object;
148 locked.m_control = nullptr;
149 locked.m_object = nullptr;
150 }
151
152 template<class T>
153 Shared<T>& Shared<T>::operator=(const Shared& other) noexcept {
154 if (this == &other)
155 return *this;
156 Shared copy(other);
157 swap(copy);
158 return *this;
159 }
160
161 template<class T>
162 Shared<T>& Shared<T>::operator=(Shared&& other) noexcept {
163 if (this == &other)
164 return *this;
165 Shared taken(std::move(other));
166 swap(taken);
167 return *this;
168 }
169
170 template<class T>
171 Shared<T>::~Shared() {
172 Release();
173 }
174
175 template<class T>
176 T* Shared<T>::get() const noexcept {
177 return m_object;
178 }
179
180 template<class T>
181 std::add_lvalue_reference_t<T> Shared<T>::operator*() const noexcept {
182 if constexpr (!std::is_void_v<T>)
183 return *m_object;
184 }
185
186 template<class T>
187 T* Shared<T>::operator->() const noexcept {
188 return m_object;
189 }
190
191 template<class T>
192 Shared<T>::operator bool() const noexcept {
193 return m_object != nullptr;
194 }
195
196 template<class T>
197 long Shared<T>::use_count() const noexcept {
198 return m_control == nullptr ? 0 : m_control->Strong.load(std::memory_order_relaxed);
199 }
200
201 template<class T>
202 void Shared<T>::reset() noexcept {
203 Release();
204 m_control = nullptr;
205 m_object = nullptr;
206 }
207
208 template<class T>
209 void Shared<T>::swap(Shared& other) noexcept {
210 using std::swap;
211 swap(m_control, other.m_control);
212 swap(m_object, other.m_object);
213 }
214
215 template<class T>
216 template<class U>
217 bool Shared<T>::owner_before(const Shared<U>& other) const noexcept {
218 return m_control < other.m_control;
219 }
220
221 template<class T>
222 template<class U>
223 bool Shared<T>::owner_before(const Weak<U>& other) const noexcept {
224 return m_control < other.m_control;
225 }
226
227 template<class T>
228 template<class Target, class... Args>
229 requires Type::SameAs<Target, T> || Type::DerivedFrom<Target, T>
230 Shared<T> Shared<T>::MakePointer(Args&&... args) {
231 return MakeShared<Target>(std::forward<Args>(args)...);
232 }
233
234 template<class T>
235 Shared<T>::Shared(Detail::Control* control, T* object) noexcept: m_control(control), m_object(object) {}
236
237 template<class T>
238 void Shared<T>::Release() noexcept {
239 Detail::ReleaseStrong(m_control);
240 }
241
242 template<class T>
243 Unique<T>::Unique() noexcept: m_object(nullptr), m_destroy(nullptr) {}
244
245 template<class T>
246 Unique<T>::Unique(std::nullptr_t) noexcept: m_object(nullptr), m_destroy(nullptr) {}
247
248 template<class T>
249 template<class U>
250 requires Type::ConvertibleTo<U*, T*>
251 Unique<T>::Unique(Unique<U>&& other) noexcept: m_object(other.m_object), m_destroy(other.m_destroy) {
252 other.m_object = nullptr;
253 other.m_destroy = nullptr;
254 }
255
256 template<class T>
257 Unique<T>::Unique(Unique&& other) noexcept: m_object(other.m_object), m_destroy(other.m_destroy) {
258 other.m_object = nullptr;
259 other.m_destroy = nullptr;
260 }
261
262 template<class T>
263 Unique<T>& Unique<T>::operator=(Unique&& other) noexcept {
264 if (this == &other)
265 return *this;
266 reset();
267 m_object = other.m_object;
268 m_destroy = other.m_destroy;
269 other.m_object = nullptr;
270 other.m_destroy = nullptr;
271 return *this;
272 }
273
274 template<class T>
275 Unique<T>::~Unique() {
276 reset();
277 }
278
279 template<class T>
280 T* Unique<T>::get() const noexcept {
281 return m_object;
282 }
283
284 template<class T>
285 std::add_lvalue_reference_t<T> Unique<T>::operator*() const noexcept {
286 if constexpr (!std::is_void_v<T>)
287 return *m_object;
288 }
289
290 template<class T>
291 T* Unique<T>::operator->() const noexcept {
292 return m_object;
293 }
294
295 template<class T>
296 Unique<T>::operator bool() const noexcept {
297 return m_object != nullptr;
298 }
299
300 template<class T>
301 void Unique<T>::reset() noexcept {
302 if (m_destroy != nullptr)
303 m_destroy(m_object);
304 m_object = nullptr;
305 m_destroy = nullptr;
306 }
307
308 template<class T>
309 void Unique<T>::swap(Unique& other) noexcept {
310 using std::swap;
311 swap(m_object, other.m_object);
312 swap(m_destroy, other.m_destroy);
313 }
314
315 template<class T>
316 template<class Target, class... Args>
317 requires Type::SameAs<Target, T> || Type::DerivedFrom<Target, T>
318 Unique<T> Unique<T>::MakePointer(Args&&... args) {
319 return MakeUnique<Target>(std::forward<Args>(args)...);
320 }
321
322 template<class T>
323 Unique<T>::Unique(T* object, void (*destroy)(void*) noexcept) noexcept: m_object(object), m_destroy(destroy) {}
324
325 template<class T>
326 Weak<T>::Weak() noexcept: m_control(nullptr), m_object(nullptr) {}
327
328 template<class T>
329 Weak<T>::Weak(std::nullptr_t) noexcept: m_control(nullptr), m_object(nullptr) {}
330
331 template<class T>
332 template<class U>
333 requires Type::ConvertibleTo<U*, T*>
334 Weak<T>::Weak(const Shared<U>& owner) noexcept: m_control(owner.m_control), m_object(owner.m_object) {
335 if (m_control != nullptr)
336 m_control->Weak.fetch_add(1, std::memory_order_relaxed);
337 }
338
339 template<class T>
340 Weak<T>::Weak(const Weak& other) noexcept: m_control(other.m_control), m_object(other.m_object) {
341 if (m_control != nullptr)
342 m_control->Weak.fetch_add(1, std::memory_order_relaxed);
343 }
344
345 template<class T>
346 Weak<T>::Weak(Weak&& other) noexcept: m_control(other.m_control), m_object(other.m_object) {
347 other.m_control = nullptr;
348 other.m_object = nullptr;
349 }
350
351 template<class T>
352 Weak<T>& Weak<T>::operator=(const Weak& other) noexcept {
353 if (this == &other)
354 return *this;
355 Weak copy(other);
356 swap(copy);
357 return *this;
358 }
359
360 template<class T>
361 Weak<T>& Weak<T>::operator=(Weak&& other) noexcept {
362 if (this == &other)
363 return *this;
364 Weak taken(std::move(other));
365 swap(taken);
366 return *this;
367 }
368
369 template<class T>
370 Weak<T>::~Weak() {
371 Release();
372 }
373
374 template<class T>
375 Shared<T> Weak<T>::lock() const noexcept {
376 if (m_control == nullptr)
377 return {};
378 long count = m_control->Strong.load(std::memory_order_relaxed);
379 while (count != 0) {
380 if (m_control->Strong.compare_exchange_weak(count, count + 1, std::memory_order_acquire, std::memory_order_relaxed))
381 return Shared<T>(m_control, m_object);
382 }
383 return {};
384 }
385
386 template<class T>
387 bool Weak<T>::expired() const noexcept {
388 return m_control == nullptr || m_control->Strong.load(std::memory_order_relaxed) == 0;
389 }
390
391 template<class T>
392 long Weak<T>::use_count() const noexcept {
393 return m_control == nullptr ? 0 : m_control->Strong.load(std::memory_order_relaxed);
394 }
395
396 template<class T>
397 void Weak<T>::reset() noexcept {
398 Release();
399 m_control = nullptr;
400 m_object = nullptr;
401 }
402
403 template<class T>
404 void Weak<T>::swap(Weak& other) noexcept {
405 using std::swap;
406 swap(m_control, other.m_control);
407 swap(m_object, other.m_object);
408 }
409
410 template<class T>
411 template<class U>
412 bool Weak<T>::owner_before(const Weak<U>& other) const noexcept {
413 return m_control < other.m_control;
414 }
415
416 template<class T>
417 template<class U>
418 bool Weak<T>::owner_before(const Shared<U>& other) const noexcept {
419 return m_control < other.m_control;
420 }
421
422 template<class T>
423 void Weak<T>::Release() noexcept {
424 Detail::ReleaseWeak(m_control);
425 }
426
427 template<class T>
428 EnableSharedFromThis<T>::EnableSharedFromThis(const EnableSharedFromThis&) noexcept {}
429
430 template<class T>
431 EnableSharedFromThis<T>::EnableSharedFromThis(EnableSharedFromThis&&) noexcept {}
432
433 template<class T>
434 EnableSharedFromThis<T>& EnableSharedFromThis<T>::operator=(const EnableSharedFromThis&) noexcept {
435 return *this;
436 }
437
438 template<class T>
439 EnableSharedFromThis<T>& EnableSharedFromThis<T>::operator=(EnableSharedFromThis&&) noexcept {
440 return *this;
441 }
442
443 template<class T>
444 Shared<T> EnableSharedFromThis<T>::SharedFromThis() const {
445 return Shared<T>(m_weak);
446 }
447
448 template<class T>
449 AtomicShared<T>::AtomicShared() noexcept: m_lock(), m_control(nullptr), m_object(nullptr) {}
450
451 template<class T>
452 AtomicShared<T>::AtomicShared(Shared<T> owner) noexcept: m_lock(), m_control(owner.m_control), m_object(owner.m_object) {
453 owner.m_control = nullptr;
454 owner.m_object = nullptr;
455 }
456
457 template<class T>
458 AtomicShared<T>::~AtomicShared() {
459 Detail::ReleaseStrong(m_control);
460 }
461
462 template<class T>
463 AtomicShared<T>& AtomicShared<T>::operator=(Shared<T> owner) noexcept {
464 store(std::move(owner));
465 return *this;
466 }
467
468 template<class T>
469 AtomicShared<T>::operator bool() const noexcept {
470 return static_cast<bool>(load());
471 }
472
473 template<class T>
474 Shared<T> AtomicShared<T>::load() const noexcept {
475 Lock();
476 Shared<T> loaded(m_control, m_object);
477 if (m_control != nullptr)
478 m_control->Strong.fetch_add(1, std::memory_order_relaxed);
479 Unlock();
480 return loaded;
481 }
482
483 template<class T>
484 void AtomicShared<T>::store(Shared<T> owner) noexcept {
485 exchange(std::move(owner));
486 }
487
488 template<class T>
489 Shared<T> AtomicShared<T>::exchange(Shared<T> owner) noexcept {
490 Lock();
491 Shared<T> previous(m_control, m_object);
492 m_control = owner.m_control;
493 m_object = owner.m_object;
494 owner.m_control = nullptr;
495 owner.m_object = nullptr;
496 Unlock();
497 return previous;
498 }
499
500 template<class T>
501 bool AtomicShared<T>::compare_exchange_strong(Shared<T>& expected, Shared<T> desired) noexcept {
502 Lock();
503 if (m_object == expected.get()) {
504 Detail::ReleaseStrong(expected.m_control);
505 expected.m_control = nullptr;
506 expected.m_object = nullptr;
507 expected = Shared<T>(m_control, m_object);
508 if (m_control != nullptr)
509 m_control->Strong.fetch_add(1, std::memory_order_relaxed);
510 Detail::ReleaseStrong(m_control);
511 m_control = desired.m_control;
512 m_object = desired.m_object;
513 desired.m_control = nullptr;
514 desired.m_object = nullptr;
515 Unlock();
516 return true;
517 }
518 Detail::ReleaseStrong(expected.m_control);
519 expected.m_control = m_control;
520 expected.m_object = m_object;
521 if (m_control != nullptr)
522 m_control->Strong.fetch_add(1, std::memory_order_relaxed);
523 Unlock();
524 return false;
525 }
526
527 template<class T>
528 bool AtomicShared<T>::compare_exchange_weak(Shared<T>& expected, Shared<T> desired) noexcept {
529 return compare_exchange_strong(expected, std::move(desired));
530 }
531
532 template<class T>
533 void AtomicShared<T>::Lock() const noexcept {
534 while (m_lock.test_and_set(std::memory_order_acquire))
535 ;
536 }
537
538 template<class T>
539 void AtomicShared<T>::Unlock() const noexcept {
540 m_lock.clear(std::memory_order_release);
541 }
542
543 template<class T, class... Args>
544 Shared<T> MakeShared(Args&&... args) {
545 try {
546 Detail::Control* control = Detail::Create<T>(std::forward<Args>(args)...);
547 Shared<T> owner(control, static_cast<T*>(control->Object));
548 if constexpr (std::is_base_of_v<EnableSharedFromThis<T>, T>)
549 static_cast<EnableSharedFromThis<T>*>(owner.get())->m_weak = owner;
550 return owner;
551 } catch (...) {
552 Heap::RethrowException();
553 }
554 }
555
556 template<class T, class... Args>
557 Unique<T> MakeUnique(Args&&... args) {
558 void* block = Heap::Allocate(sizeof(T));
559 try {
560 T* object = new (block) T(std::forward<Args>(args)...);
561 return Unique<T>(object, [](void* pointer) noexcept {
562 static_cast<T*>(pointer)->~T();
563 Heap::Free(pointer);
564 });
565 } catch (...) {
566 Heap::Free(block);
567 Heap::RethrowException();
568 }
569 }
570
571 template<class T, class U>
572 Shared<T> StaticPointerCast(const Shared<U>& from) noexcept {
573 if (!from)
574 return {};
575 Shared<T> casted(from.m_control, static_cast<T*>(from.get()));
576 casted.m_control->Strong.fetch_add(1, std::memory_order_relaxed);
577 return casted;
578 }
579
580 template<class T, class U>
581 Shared<T> DynamicPointerCast(const Shared<U>& from) noexcept {
582 if (!from)
583 return {};
584 T* object = dynamic_cast<T*>(from.get());
585 if (object == nullptr)
586 return {};
587 Shared<T> casted(from.m_control, object);
588 casted.m_control->Strong.fetch_add(1, std::memory_order_relaxed);
589 return casted;
590 }
591
592 template<class T, class U>
593 Shared<T> ConstPointerCast(const Shared<U>& from) noexcept {
594 if (!from)
595 return {};
596 Shared<T> casted(from.m_control, const_cast<T*>(from.get()));
597 casted.m_control->Strong.fetch_add(1, std::memory_order_relaxed);
598 return casted;
599 }
600
601 template<class T, class U>
602 Shared<T> ReinterpretPointerCast(const Shared<U>& from) noexcept {
603 if (!from)
604 return {};
605 Shared<T> casted(from.m_control, reinterpret_cast<T*>(from.get()));
606 casted.m_control->Strong.fetch_add(1, std::memory_order_relaxed);
607 return casted;
608 }
609
610 template<class T>
611 void swap(Shared<T>& left, Shared<T>& right) noexcept {
612 left.swap(right);
613 }
614
615 template<class T>
616 void swap(Unique<T>& left, Unique<T>& right) noexcept {
617 left.swap(right);
618 }
619
620 template<class T>
621 void swap(Weak<T>& left, Weak<T>& right) noexcept {
622 left.swap(right);
623 }
624 }
625}