db/skiplist.h

filter: Statementstmt 72.1% 83 / 115 Branchbran 52.6% 40 / 76 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 64.4% 123 / 191 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« db/log_writer.cc ↑ Summary db/version_set.h »
1 // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. See the AUTHORS file for names of contributors.
4 //
5 // Thread safety
6 // -------------
7 //
8 // Writes require external synchronization, most likely a mutex.
9 // Reads require a guarantee that the SkipList will not be destroyed
10 // while the read is in progress. Apart from that, reads progress
11 // without any internal locking or synchronization.
12 //
13 // Invariants:
14 //
15 // (1) Allocated nodes are never deleted until the SkipList is
16 // destroyed. This is trivially guaranteed by the code since we
17 // never delete any skip list nodes.
18 //
19 // (2) The contents of a Node except for the next/prev pointers are
20 // immutable after the Node has been linked into the SkipList.
21 // Only Insert() modifies the list, and it is careful to initialize
22 // a node and use release-stores to publish the nodes in one or
23 // more lists.
24 //
25 // ... prev vs. next pointer ordering ...
26  
27 #include <assert.h>
28 #include <stdlib.h>
29 #include "port/port.h"
30 #include "util/arena.h"
31 #include "util/random.h"
32  
33 namespace leveldb {
34  
35 class Arena;
36  
37 template<typename Key, class Comparator>
38 class SkipList {
39 private:
40 struct Node;
41  
42 public:
43 // Create a new SkipList object that will use "cmp" for comparing keys,
44 // and will allocate memory using "*arena". Objects allocated in the arena
45 // must remain allocated for the lifetime of the skiplist object.
46 explicit SkipList(Comparator cmp, Arena* arena);
47  
48 // Insert key into the list.
49 // REQUIRES: nothing that compares equal to key is currently in the list.
50 void Insert(const Key& key);
51  
52 // Returns true iff an entry that compares equal to key is in the list.
53 bool Contains(const Key& key) const;
54  
55 // Iteration over the contents of a skip list
56 class Iterator {
57 public:
58 // Initialize an iterator over the specified list.
59 // The returned iterator is not valid.
60 explicit Iterator(const SkipList* list);
61  
62 // Returns true iff the iterator is positioned at a valid node.
63 bool Valid() const;
64  
65 // Returns the key at the current position.
66 // REQUIRES: Valid()
67 const Key& key() const;
68  
69 // Advances to the next position.
70 // REQUIRES: Valid()
71 void Next();
72  
73 // Advances to the previous position.
74 // REQUIRES: Valid()
75 void Prev();
76  
77 // Advance to the first entry with a key >= target
78 void Seek(const Key& target);
79  
80 // Position at the first entry in list.
81 // Final state of iterator is Valid() iff list is not empty.
82 void SeekToFirst();
83  
84 // Position at the last entry in list.
85 // Final state of iterator is Valid() iff list is not empty.
86 void SeekToLast();
87  
88 private:
89 const SkipList* list_;
90 Node* node_;
91 // Intentionally copyable
92 };
93  
94 private:
95 enum { kMaxHeight = 12 };
96  
97 // Immutable after construction
98 Comparator const compare_;
99 Arena* const arena_; // Arena used for allocations of nodes
100  
101 Node* const head_;
102  
103 // Modified only by Insert(). Read racily by readers, but stale
104 // values are ok.
105 port::AtomicPointer max_height_; // Height of the entire list
106  
107 80 inline int GetMaxHeight() const {
108 80 return reinterpret_cast<intptr_t>(max_height_.NoBarrier_Load());
109 }
110  
111 // Read/written only by Insert().
112 Random rnd_;
113  
114 Node* NewNode(const Key& key, int height);
115 int RandomHeight();
116 25 bool Equal(const Key& a, const Key& b) const { return (compare_(a, b) == 0); }
117  
118 // Return true if key is greater than the data stored in "n"
119 bool KeyIsAfterNode(const Key& key, Node* n) const;
120  
121 // Return the earliest node that comes at or after key.
122 // Return NULL if there is no such node.
123 //
124 // If prev is non-NULL, fills prev[level] with pointer to previous
125 // node at "level" for every level in [0..max_height_-1].
126 Node* FindGreaterOrEqual(const Key& key, Node** prev) const;
127  
128 // Return the latest node with a key < key.
129 // Return head_ if there is no such node.
130 Node* FindLessThan(const Key& key) const;
131  
132 // Return the last node in the list.
133 // Return head_ if list is empty.
134 Node* FindLast() const;
135  
136 // No copying allowed
137 SkipList(const SkipList&);
138 void operator=(const SkipList&);
139 };
140  
141 // Implementation details follow
142 template<typename Key, class Comparator>
143 struct SkipList<Key,Comparator>::Node {
144 72 ▶ explicit Node(const Key& k) : key(k) { }
Branch: 1 branch
BranchTrueFalseTotal
explicit Node(const Key& k) : key(k) { } 36 36 72
145  
146 Key const key;
147  
148 // Accessors/mutators for links. Wrapped in methods so we can
149 // add the appropriate barriers as necessary.
150 208 Node* Next(int n) {
151 208 ▶ assert(n >= 0);
Branch: 1 branch
BranchTrueFalseTotal
assert(n >= 0); 0 208 208
152 // Use an 'acquire load' so that we observe a fully initialized
153 // version of the returned Node.
154 208 return reinterpret_cast<Node*>(next_[n].Acquire_Load());
155 }
156 97 void SetNext(int n, Node* x) {
157 97 ▶ assert(n >= 0);
Branch: 1 branch
BranchTrueFalseTotal
assert(n >= 0); 0 97 97
158 // Use a 'release store' so that anybody who reads through this
159 // pointer observes a fully initialized version of the inserted node.
160 97 next_[n].Release_Store(x);
161 97 }
162  
163 // No-barrier variants that can be safely used in a few locations.
164 37 Node* NoBarrier_Next(int n) {
165 37 ▶ assert(n >= 0);
Branch: 1 branch
BranchTrueFalseTotal
assert(n >= 0); 0 37 37
166 37 return reinterpret_cast<Node*>(next_[n].NoBarrier_Load());
167 }
168 37 void NoBarrier_SetNext(int n, Node* x) {
169 37 ▶ assert(n >= 0);
Branch: 1 branch
BranchTrueFalseTotal
assert(n >= 0); 0 37 37
170 37 next_[n].NoBarrier_Store(x);
171 37 }
172  
173 private:
174 // Array of length equal to the node height. next_[0] is lowest level link.
175 port::AtomicPointer next_[1];
176 };
177  
178 template<typename Key, class Comparator>
179 typename SkipList<Key,Comparator>::Node*
180 36 SkipList<Key,Comparator>::NewNode(const Key& key, int height) {
181 72 char* mem = arena_->AllocateAligned(
182 36 sizeof(Node) + sizeof(port::AtomicPointer) * (height - 1));
183 36 return new (mem) Node(key);
184 }
185  
186 template<typename Key, class Comparator>
187 23 inline SkipList<Key,Comparator>::Iterator::Iterator(const SkipList* list) {
188 23 list_ = list;
189 23 node_ = NULL;
190 23 }
191  
192 template<typename Key, class Comparator>
193 338 inline bool SkipList<Key,Comparator>::Iterator::Valid() const {
194 338 return node_ != NULL;
195 }
196  
197 template<typename Key, class Comparator>
198 127 inline const Key& SkipList<Key,Comparator>::Iterator::key() const {
199 127 ▶ assert(Valid());
Branch: 1 branch
BranchTrueFalseTotal
assert(Valid()); 0 127 127
200 127 return node_->key;
201 }
202  
203 template<typename Key, class Comparator>
204 83 inline void SkipList<Key,Comparator>::Iterator::Next() {
205 83 ▶ assert(Valid());
Branch: 1 branch
BranchTrueFalseTotal
assert(Valid()); 0 83 83
206 83 node_ = node_->Next(0);
207 83 }
208  
209 template<typename Key, class Comparator>
210 0 inline void SkipList<Key,Comparator>::Iterator::Prev() {
211 // Instead of using explicit "prev" links, we just search for the
212 // last node that falls before key.
213 0 ▶ assert(Valid());
Branch: 1 branch
BranchTrueFalseTotal
assert(Valid()); 0 0 0
214 0 node_ = list_->FindLessThan(node_->key);
215 0 ▶ if (node_ == list_->head_) {
Branch: 1 branch
BranchTrueFalseTotal
if (node_ == list_->head_) { 0 0 0
216 0 node_ = NULL;
217 }
218 0 }
219  
220 template<typename Key, class Comparator>
221 14 inline void SkipList<Key,Comparator>::Iterator::Seek(const Key& target) {
222 14 node_ = list_->FindGreaterOrEqual(target, NULL);
223 14 }
224  
225 template<typename Key, class Comparator>
226 9 inline void SkipList<Key,Comparator>::Iterator::SeekToFirst() {
227 9 node_ = list_->head_->Next(0);
228 9 }
229  
230 template<typename Key, class Comparator>
231 0 inline void SkipList<Key,Comparator>::Iterator::SeekToLast() {
232 0 node_ = list_->FindLast();
233 0 ▶ if (node_ == list_->head_) {
Branch: 1 branch
BranchTrueFalseTotal
if (node_ == list_->head_) { 0 0 0
234 0 node_ = NULL;
235 }
236 0 }
237  
238 template<typename Key, class Comparator>
239 31 int SkipList<Key,Comparator>::RandomHeight() {
240 // Increase height with probability 1 in kBranching
241 static const unsigned int kBranching = 4;
242 31 int height = 1;
243 37 ▶ while (height < kMaxHeight && ((rnd_.Next() % kBranching) == 0)) {
Branch: 3 branches
BranchTrueFalseTotal
while (height < kMaxHeight && ((rnd_.Next() % kBranching) == 0)) { 37 0 37
while (height < kMaxHeight && ((rnd_.Next() % kBranching) == 0)) { 6 31 37
while (height < kMaxHeight && ((rnd_.Next() % kBranching) == 0)) { 6 31 37
244 6 height++;
245 }
246 31 ▶ assert(height > 0);
Branch: 1 branch
BranchTrueFalseTotal
assert(height > 0); 0 31 31
247 31 ▶ assert(height <= kMaxHeight);
Branch: 1 branch
BranchTrueFalseTotal
assert(height <= kMaxHeight); 0 31 31
248 31 return height;
249 }
250  
251 template<typename Key, class Comparator>
252 116 bool SkipList<Key,Comparator>::KeyIsAfterNode(const Key& key, Node* n) const {
253 // NULL n is considered infinite
254 116 ▶ return (n != NULL) && (compare_(n->key, key) < 0);
Branch: 2 branches
BranchTrueFalseTotal
return (n != NULL) && (compare_(n->key, key) < 0); 103 13 116
return (n != NULL) && (compare_(n->key, key) < 0); 33 70 103
255 }
256  
257 template<typename Key, class Comparator>
258 45 typename SkipList<Key,Comparator>::Node* SkipList<Key,Comparator>::FindGreaterOrEqual(const Key& key, Node** prev)
259 const {
260 45 Node* x = head_;
261 45 int level = GetMaxHeight() - 1;
262 71 while (true) {
263 116 Node* next = x->Next(level);
264 116 ▶ if (KeyIsAfterNode(key, next)) {
Branch: 1 branch
BranchTrueFalseTotal
if (KeyIsAfterNode(key, next)) { 33 83 116
265 // Keep searching in this list
266 33 x = next;
267 } else {
268 83 ▶ if (prev != NULL) prev[level] = x;
Branch: 1 branch
BranchTrueFalseTotal
if (prev != NULL) prev[level] = x; 58 25 83
269 83 ▶ if (level == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (level == 0) { 45 38 83
270 45 return next;
271 } else {
272 // Switch to next list
273 38 level--;
274 }
275 }
276 }
277 }
278  
279 template<typename Key, class Comparator>
280 typename SkipList<Key,Comparator>::Node*
281 0 SkipList<Key,Comparator>::FindLessThan(const Key& key) const {
282 0 Node* x = head_;
283 0 int level = GetMaxHeight() - 1;
284 0 while (true) {
285 0 ▶ assert(x == head_ || compare_(x->key, key) < 0);
Branch: 2 branches
BranchTrueFalseTotal
assert(x == head_ || compare_(x->key, key) < 0); 0 0 0
assert(x == head_ || compare_(x->key, key) < 0); 0 0 0
286 0 Node* next = x->Next(level);
287 0 ▶ if (next == NULL || compare_(next->key, key) >= 0) {
Branch: 3 branches
BranchTrueFalseTotal
if (next == NULL || compare_(next->key, key) >= 0) { 0 0 0
if (next == NULL || compare_(next->key, key) >= 0) { 0 0 0
if (next == NULL || compare_(next->key, key) >= 0) { 0 0 0
288 0 ▶ if (level == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (level == 0) { 0 0 0
289 0 return x;
290 } else {
291 // Switch to next list
292 0 level--;
293 }
294 } else {
295 0 x = next;
296 }
297 }
298 }
299  
300 template<typename Key, class Comparator>
301 0 typename SkipList<Key,Comparator>::Node* SkipList<Key,Comparator>::FindLast()
302 const {
303 0 Node* x = head_;
304 0 int level = GetMaxHeight() - 1;
305 0 while (true) {
306 0 Node* next = x->Next(level);
307 0 ▶ if (next == NULL) {
Branch: 1 branch
BranchTrueFalseTotal
if (next == NULL) { 0 0 0
308 0 ▶ if (level == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (level == 0) { 0 0 0
309 0 return x;
310 } else {
311 // Switch to next list
312 0 level--;
313 }
314 } else {
315 0 x = next;
316 }
317 }
318 }
319  
320 template<typename Key, class Comparator>
321 5 SkipList<Key,Comparator>::SkipList(Comparator cmp, Arena* arena)
322 5 : compare_(cmp),
323 5 arena_(arena),
324 5 ▶ head_(NewNode(0 /* any key will do */, kMaxHeight)),
Branch: 1 branch
BranchTrueFalseTotal
head_(NewNode(0 /* any key will do */, kMaxHeight)), 5 0 5
325 5 max_height_(reinterpret_cast<void*>(1)),
326 5 rnd_(0xdeadbeef) {
327 65 ▶ for (int i = 0; i < kMaxHeight; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (int i = 0; i < kMaxHeight; i++) { 60 5 65
328 60 head_->SetNext(i, NULL);
329 }
330 5 }
331  
332 template<typename Key, class Comparator>
333 31 void SkipList<Key,Comparator>::Insert(const Key& key) {
334 // TODO(opt): We can use a barrier-free variant of FindGreaterOrEqual()
335 // here since Insert() is externally synchronized.
336 Node* prev[kMaxHeight];
337 31 ▶ Node* x = FindGreaterOrEqual(key, prev);
Branch: 1 branch
BranchTrueFalseTotal
Node* x = FindGreaterOrEqual(key, prev); 31 0 31
338  
339 // Our data structure does not allow duplicate insertion
340 31 ▶ assert(x == NULL || !Equal(key, x->key));
Branch: 3 branches
BranchTrueFalseTotal
assert(x == NULL || !Equal(key, x->key)); 25 6 31
assert(x == NULL || !Equal(key, x->key)); 25 0 25
assert(x == NULL || !Equal(key, x->key)); 0 25 25
341  
342 31 int height = RandomHeight();
343 31 ▶ if (height > GetMaxHeight()) {
Branch: 1 branch
BranchTrueFalseTotal
if (height > GetMaxHeight()) { 4 27 31
344 8 ▶ for (int i = GetMaxHeight(); i < height; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (int i = GetMaxHeight(); i < height; i++) { 4 4 8
345 4 prev[i] = head_;
346 }
347 //fprintf(stderr, "Change height from %d to %d\n", max_height_, height);
348  
349 // It is ok to mutate max_height_ without any synchronization
350 // with concurrent readers. A concurrent reader that observes
351 // the new value of max_height_ will see either the old value of
352 // new level pointers from head_ (NULL), or a new value set in
353 // the loop below. In the former case the reader will
354 // immediately drop to the next level since NULL sorts after all
355 // keys. In the latter case the reader will use the new node.
356 4 max_height_.NoBarrier_Store(reinterpret_cast<void*>(height));
357 }
358  
359 31 ▶ x = NewNode(key, height);
Branch: 1 branch
BranchTrueFalseTotal
x = NewNode(key, height); 31 0 31
360 68 ▶ for (int i = 0; i < height; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (int i = 0; i < height; i++) { 37 31 68
361 // NoBarrier_SetNext() suffices since we will add a barrier when
362 // we publish a pointer to "x" in prev[i].
363 37 x->NoBarrier_SetNext(i, prev[i]->NoBarrier_Next(i));
364 37 prev[i]->SetNext(i, x);
365 }
366 31 }
367  
368 template<typename Key, class Comparator>
369 bool SkipList<Key,Comparator>::Contains(const Key& key) const {
370 Node* x = FindGreaterOrEqual(key, NULL);
371 if (x != NULL && Equal(key, x->key)) {
372 return true;
373 } else {
374 return false;
375 }
376 }
377  
378 }
« db/log_writer.cc ↑ Summary db/version_set.h »