| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | #pragma once |
| 4 | |
| 5 | #include <atomic> |
| 6 | #include <cstddef> |
| 7 | |
| 8 | namespace mos |
| 9 | { |
| 10 | struct RCCore |
| 11 | { |
| 12 | std::atomic_size_t n = 0; |
| 13 | void Ref() |
| 14 | { |
| 15 | n++; |
| 16 | } |
| 17 | |
| 18 | void Unref() |
| 19 | { |
| 20 | n--; |
| 21 | } |
| 22 | }; |
| 23 | |
| 24 | struct RefCounted |
| 25 | { |
| 26 | protected: |
| 27 | explicit RefCounted(RCCore *rc_) : rc(rc_) |
| 28 | { |
| 29 | rc->Ref(); |
| 30 | } |
| 31 | |
| 32 | RefCounted(const RefCounted &a) : rc(a.rc) |
| 33 | { |
| 34 | rc->Ref(); |
| 35 | } |
| 36 | |
| 37 | RefCounted(RefCounted &&a) : rc(a.rc) |
| 38 | { |
| 39 | a.rc = nullptr; |
| 40 | } |
| 41 | |
| 42 | ~RefCounted() |
| 43 | { |
| 44 | if (rc) |
| 45 | { |
| 46 | rc->Unref(); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | RefCounted operator=(const RefCounted &a) = delete; |
| 51 | RefCounted operator=(RefCounted &&a) = delete; |
| 52 | |
| 53 | protected: |
| 54 | size_t GetRef() const |
| 55 | { |
| 56 | return rc->n; |
| 57 | } |
| 58 | |
| 59 | private: |
| 60 | RCCore *rc = nullptr; |
| 61 | }; |
| 62 | } // namespace mos |
| 63 | |