forked from scylladb/scylladb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentangled.hh
99 lines (88 loc) · 2.62 KB
/
entangled.hh
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
/*
* Copyright (C) 2020 ScyllaDB
*/
/*
* SPDX-License-Identifier: LicenseRef-ScyllaDB-Source-Available-1.0
*/
#pragma once
#include "utils/assert.hh"
#include <boost/intrusive/parent_from_member.hpp>
#include <assert.h>
// A movable pointer-like object paired with exactly one other object of the same type.
// The two objects which are paired with each other point at each other.
// The relationship is symmetrical.
//
// A pair of such objects can be used for implementing bi-directional traversal in data structures.
//
// Moving this object automatically updates the other reference, so the references remain
// consistent when the containing objects are managed by LSA.
//
// get()
// ------------------>
// ----------- -----------
// | entangled |~~~~~~~~~~~| entangled |
// ----------- -----------
// <------------------
// get()
//
class entangled final {
entangled* _ref = nullptr;
private:
struct init_tag {};
entangled(init_tag, entangled& other) {
SCYLLA_ASSERT(!other._ref);
_ref = &other;
other._ref = this;
}
public:
// Creates a new object which is paired with a given "other".
// The other is also paired with this object afterwards.
// The other must not be paired before the call.
static entangled make_paired_with(entangled& other) {
return entangled(init_tag(), other);
}
// Creates an unpaired object.
entangled() = default;
entangled(const entangled&) = delete;
entangled(entangled&& other) noexcept
: _ref(other._ref)
{
if (_ref) {
_ref->_ref = this;
}
other._ref = nullptr;
}
~entangled() {
if (_ref) {
_ref->_ref = nullptr;
}
}
entangled& operator=(entangled&& other) noexcept {
if (_ref) {
_ref->_ref = nullptr;
}
_ref = other._ref;
if (_ref) {
_ref->_ref = this;
}
other._ref = nullptr;
return *this;
}
entangled* get() { return _ref; }
const entangled* get() const { return _ref; }
explicit operator bool() const { return _ref != nullptr; }
template<typename T>
T* get(entangled T::* paired_member) {
if (!_ref) {
return nullptr;
}
return boost::intrusive::get_parent_from_member(get(), paired_member);
}
template<typename T>
const T* get(entangled T::* paired_member) const {
if (!_ref) {
return nullptr;
}
return boost::intrusive::get_parent_from_member(get(), paired_member);
}
};