-
Notifications
You must be signed in to change notification settings - Fork 4
/
set.h
146 lines (111 loc) · 2.65 KB
/
set.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
#ifndef LITE__SET_H
#define LITE__SET_H
#include <lace/do_not_copy.h>
#include "link.h"
#include <cassert>
#include <cstddef>
#include <algorithm>
namespace lite {
template <class X>
struct set_link {
typedef set_link type;
template <class T, typename set_link<T>::type T::*L>
friend class set;
bool bound() const {
assert(p.p || !n.p);
return p.p;
}
private:
link_tag<X> p;
link<X> n;
};
template <class T, typename set_link<T>::type T::*L>
class set : public lace::do_not_copy {
public:
set() : head(NULL), tail(&head), rank(0) { }
~set() { assert(empty()); }
bool empty() const { return !head; }
set & join(T* t) {
assert(!typed(t));
assert(!empty() || &head == tail);
if (!empty()) {
(t->*L).p.p = head;
} else {
if (!rank)
++rank;
(t->*L).p.tag(reinterpret_cast<T*>(this));
}
*tail = t;
tail = &(t->*L).n.p;
*tail = t;
assert(typed(t));
assert(!empty());
return *this;
}
static bool typed(const T* t) { return (t->*L).bound(); }
static set* archetype(const T* t) {
assert(typed(t));
while (!(t->*L).p.tagged()) {
const T* p = (t->*L).p.p;
if (!(p->*L).p.tagged()) // compress path
(const_cast<T*>(t)->*L).p.p = (p->*L).p.p;
t = p;
}
return reinterpret_cast<set*>((t->*L).p.tagless());
}
bool contains(const T* t) const {
assert(typed(t));
return this == archetype(t);
}
set* conjoin(set* that) {
assert(this != that);
if (that->empty())
return that;
// union by rank
if (empty() || rank < that->rank) {
std::swap(head, that->head);
std::swap(tail, that->tail);
std::swap(rank, that->rank);
(head->*L).p.tag(reinterpret_cast<T*>(this));
} else if (rank == that->rank)
++rank;
if (!that->empty()) {
assert((head->*L).p.tagged());
(that->head->*L).p.p = head;
*tail = that->head;
tail = that->tail;
}
that->head = NULL;
that->tail = &that->head;
that->rank = 0;
assert(that->empty());
return that;
}
typedef void (T::*dissolver_t)();
set & dissolve(const dissolver_t d = NULL) {
while (T* t = head) {
assert(typed(t));
head = (t->*L).n.qualified(t != *tail);
(t->*L).p.p = NULL;
(t->*L).n.p = NULL;
assert(!typed(t));
if (d)
(t->*d)();
}
tail = &head;
rank = 0;
assert(empty());
return *this;
}
T* iterator() const { return head; }
T* next(const T* t) const {
assert(contains(t));
return (t->*L).n.qualified(t != *tail);
}
private:
T * head;
T ** tail;
unsigned rank;
};
} // namespace lite
#endif//LITE__SET_H