-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConsList.h
130 lines (96 loc) · 1.78 KB
/
ConsList.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
#ifndef CONS_LIST_H
#define CONS_LIST_H
#include <cassert>
namespace ImmutableCPP
{
/*
TODO: Thread safety (just need a thread safe integer)
*/
template<typename T>
class ConsList
{public:
ConsList()
: head(0)
{
}
ConsList(ConsList const&o)
: head(o.head ? o.head->reference() : 0)
{
}
ConsList &operator=(ConsList const&o)
{
this->~ConsList();
this->head = o.head;
if(this->head)
this->head->reference();
return *this;
}
~ConsList()
{
// Non-recursive GC: we walk the list iteratively, dereferencing each node we arrive to. If the refcount goes to 0, then we continue. If not, we stop
for(ConsListNode *node = head;
node;)
{
ConsListNode *next = node->next;
if(!node->dereference())
break;
node = next;
}
head = 0;
}
ConsList cons(T const&value)const
{
return ConsList(new ConsListNode(value, head));
}
ConsList rest()const
{
assert(head);
return ConsList(head->next);
}
T const&first()const
{
assert(head);
return head->value;
}
bool empty()const
{
return head == 0;
}
// TODO: Length
private:
class ConsListNode
{public:
ConsListNode(T const&value, ConsListNode *next)
: refs(0), value(value), next(next?next->reference():0)
{
}
ConsListNode *reference()
{
++refs;
return this;
}
/**
* @return Whether or not the node was destroyed
*/
bool dereference()
{
if((--refs) == 0)
{
delete this;
return true;
}
return false;
}
const T value;
ConsListNode *const next;
private:
size_t refs;
};
ConsList(ConsListNode *head)
: head(head?head->reference():0)
{
}
ConsListNode *head;
};
};
#endif//CONS_LIST_H