-
-
Notifications
You must be signed in to change notification settings - Fork 145
/
gc_list.h
498 lines (408 loc) · 10.8 KB
/
gc_list.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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
#ifndef MYCPP_GC_LIST_H
#define MYCPP_GC_LIST_H
#include <string.h> // memcpy
#include <algorithm> // sort() is templated
#include "mycpp/common.h" // DCHECK
#include "mycpp/comparators.h"
#include "mycpp/gc_alloc.h" // Alloc
#include "mycpp/gc_builtins.h" // ValueError
#include "mycpp/gc_slab.h"
// GlobalList layout-compatible with List (unit tests assert this), and it can
// be a true C global (incurs zero startup time)
template <typename T, int N>
class GlobalList {
public:
ObjHeader header_;
int len_;
int capacity_;
GlobalSlab<T, N>* slab_;
};
template <typename T>
class List {
// Relate slab size to number of items (capacity)
// 8 / 4 = 2 items, or 8 / 8 = 1 item
static const int kCapacityAdjust = kSlabHeaderSize / sizeof(T);
static_assert(kSlabHeaderSize % sizeof(T) == 0,
"Slab header size should be multiple of item size");
// Relates to minimum Slab size.
// Smallest non-empty List<T*> should have about 4 items, or 3 without header
// Smallest non-empty List<int> should have about 8 items, or 7 without header
static const int kMinItems = 32 / sizeof(T);
static_assert(32 % sizeof(T) == 0,
"An integral number of items should fit in 32 bytes");
public:
List()
: GC_CLASS_FIXED(header_, field_mask(), sizeof(List<T>)),
len_(0),
capacity_(0),
slab_(nullptr) {
}
// Implements L[i]
T index_(int i);
// returns index of the element
int index(T element);
// Implements L[i] = item
void set(int i, T item);
// L[begin:]
List* slice(int begin);
// L[begin:end]
List* slice(int begin, int end);
// Should we have a separate API that doesn't return it?
// https://stackoverflow.com/questions/12600330/pop-back-return-value
T pop();
// Used in osh/word_parse.py to remove from front
T pop(int i);
// Remove the first occourence of x from the list.
void remove(T x);
void clear();
// Used in osh/string_ops.py
void reverse();
// Templated function
void sort();
// Ensure that there's space for a number of items
void reserve(int n);
// Append a single element to this list.
void append(T item);
// Extend this list with multiple elements.
void extend(List<T>* other);
GC_OBJ(header_);
int len_; // number of entries
int capacity_; // max entries before resizing
// The container may be resized, so this field isn't in-line.
Slab<T>* slab_;
// A list has one Slab pointer which we need to follow.
static constexpr uint16_t field_mask() {
return maskbit(offsetof(List, slab_));
}
DISALLOW_COPY_AND_ASSIGN(List)
private:
int RoundCapacity(int n) {
if (n < kMinItems) {
return kMinItems;
}
return RoundUp(n);
}
};
// "Constructors" as free functions since we can't allocate within a
// constructor. Allocation may cause garbage collection, which interferes with
// placement new.
// This is not really necessary, only syntactic sugar.
template <typename T>
List<T>* NewList() {
return Alloc<List<T>>();
}
// Literal ['foo', 'bar']
// This seems to allow better template argument type deduction than a
// constructor.
template <typename T>
List<T>* NewList(std::initializer_list<T> init) {
auto self = Alloc<List<T>>();
int n = init.size();
self->reserve(n);
int i = 0;
for (auto item : init) {
self->set(i, item);
++i;
}
self->len_ = n;
return self;
}
// ['foo'] * 3
template <typename T>
List<T>* NewList(T item, int times) {
auto self = Alloc<List<T>>();
self->reserve(times);
self->len_ = times;
for (int i = 0; i < times; ++i) {
self->set(i, item);
}
return self;
}
template <typename T>
void List<T>::append(T item) {
reserve(len_ + 1);
set(len_, item);
++len_;
}
template <typename T>
int len(const List<T>* L) {
return L->len_;
}
template <typename T>
List<T>* list_repeat(T item, int times);
template <typename T>
inline bool list_contains(List<T>* haystack, T needle);
template <typename K, typename V>
class Dict; // forward decl
template <typename V>
List<Str*>* sorted(Dict<Str*, V>* d);
template <typename T>
List<T>* sorted(List<T>* l);
// L[begin:]
// TODO: Implement this in terms of slice(begin, end)
template <typename T>
List<T>* List<T>::slice(int begin) {
if (begin < 0) {
begin = len_ + begin;
}
DCHECK(begin >= 0);
List<T>* result = nullptr;
result = NewList<T>();
for (int i = begin; i < len_; i++) {
result->append(slab_->items_[i]);
}
return result;
}
// L[begin:end]
template <typename T>
List<T>* List<T>::slice(int begin, int end) {
if (begin < 0) {
begin = len_ + begin;
}
if (end < 0) {
end = len_ + end;
}
DCHECK(end <= len_);
DCHECK(begin >= 0);
DCHECK(end >= 0);
List<T>* result = NewList<T>();
for (int i = begin; i < end; i++) {
result->append(slab_->items_[i]);
}
return result;
}
// Ensure that there's space for a number of items
template <typename T>
void List<T>::reserve(int n) {
// log("reserve capacity = %d, n = %d", capacity_, n);
// Don't do anything if there's already enough space.
if (capacity_ >= n) {
return;
}
// Slabs should be a total of 2^N bytes. kCapacityAdjust is the number of
// items that the 8 byte header takes up: 1 for List<T*>, and 2 for
// List<int>.
//
// Example: the user reserves space for 3 integers. The minimum number of
// items would be 5, which is rounded up to 8. Subtract 2 again, giving 6,
// which leads to 8 + 6*4 = 32 byte Slab.
capacity_ = RoundCapacity(n + kCapacityAdjust) - kCapacityAdjust;
auto new_slab = NewSlab<T>(capacity_);
if (len_ > 0) {
// log("Copying %d bytes", len_ * sizeof(T));
memcpy(new_slab->items_, slab_->items_, len_ * sizeof(T));
}
slab_ = new_slab;
}
// Implements L[i] = item
template <typename T>
void List<T>::set(int i, T item) {
if (i < 0) {
i = len_ + i;
}
DCHECK(i >= 0);
DCHECK(i < capacity_);
slab_->items_[i] = item;
}
// Implements L[i]
template <typename T>
T List<T>::index_(int i) {
if (i < 0) {
int j = len_ + i;
if (j >= len_ || j < 0) {
throw Alloc<IndexError>();
}
return slab_->items_[j];
}
if (i >= len_ || i < 0) {
throw Alloc<IndexError>();
}
return slab_->items_[i];
}
// L.index(i) -- Python method
template <typename T>
int List<T>::index(T value) {
int element_count = len(this);
for (int i = 0; i < element_count; i++) {
if (are_equal(slab_->items_[i], value)) {
return i;
}
}
throw Alloc<ValueError>();
}
// Should we have a separate API that doesn't return it?
// https://stackoverflow.com/questions/12600330/pop-back-return-value
template <typename T>
T List<T>::pop() {
if (len_ == 0) {
throw Alloc<IndexError>();
}
len_--;
T result = slab_->items_[len_];
slab_->items_[len_] = 0; // zero for GC scan
return result;
}
// Used in osh/word_parse.py to remove from front
template <typename T>
T List<T>::pop(int i) {
if (len_ < i) {
throw Alloc<IndexError>();
}
T result = index_(i);
len_--;
// Shift everything by one
memmove(slab_->items_ + i, slab_->items_ + (i + 1), len_ * sizeof(T));
/*
for (int j = 0; j < len_; j++) {
slab_->items_[j] = slab_->items_[j+1];
}
*/
slab_->items_[len_] = 0; // zero for GC scan
return result;
}
template <typename T>
void List<T>::remove(T x) {
int idx = this->index(x);
this->pop(idx); // unused
}
template <typename T>
void List<T>::clear() {
memset(slab_->items_, 0, len_ * sizeof(T)); // zero for GC scan
len_ = 0;
}
// Used in osh/string_ops.py
template <typename T>
void List<T>::reverse() {
for (int i = 0; i < len_ / 2; ++i) {
// log("swapping %d and %d", i, n-i);
T tmp = slab_->items_[i];
int j = len_ - 1 - i;
slab_->items_[i] = slab_->items_[j];
slab_->items_[j] = tmp;
}
}
// Extend this list with multiple elements.
template <typename T>
void List<T>::extend(List<T>* other) {
int n = other->len_;
int new_len = len_ + n;
reserve(new_len);
for (int i = 0; i < n; ++i) {
set(len_ + i, other->slab_->items_[i]);
}
len_ = new_len;
}
inline bool _cmp(Str* a, Str* b) {
return mylib::str_cmp(a, b) < 0;
}
template <typename T>
void List<T>::sort() {
std::sort(slab_->items_, slab_->items_ + len_, _cmp);
}
// TODO: mycpp can just generate the constructor instead?
// e.g. [None] * 3
template <typename T>
List<T>* list_repeat(T item, int times) {
return NewList<T>(item, times);
}
// e.g. 'a' in ['a', 'b', 'c']
template <typename T>
inline bool list_contains(List<T>* haystack, T needle) {
int n = len(haystack);
for (int i = 0; i < n; ++i) {
if (are_equal(haystack->index_(i), needle)) {
return true;
}
}
return false;
}
template <typename V>
List<Str*>* sorted(Dict<Str*, V>* d) {
auto keys = d->keys();
keys->sort();
return keys;
}
template <typename T>
List<T>* sorted(List<T>* l) {
auto ret = list(l);
ret->sort();
return ret;
}
// list(L) copies the list
template <typename T>
List<T>* list(List<T>* other) {
auto result = NewList<T>();
result->extend(other);
return result;
}
#define GLOBAL_LIST(T, N, name, array) \
GlobalSlab<T, N> _slab_##name = { \
{kIsHeader, 0, kZeroMask, HeapTag::Global, kNoObjLen}, array}; \
GlobalList<T, N> _list_##name = { \
{kIsHeader, 0, kZeroMask, HeapTag::Global, kNoObjLen}, \
N, \
N, \
&_slab_##name}; \
List<T>* name = reinterpret_cast<List<T>*>(&_list_##name);
template <class T>
class ListIter {
public:
explicit ListIter(List<T>* L) : L_(L), i_(0) {
// Cheney only: L_ could be moved during iteration.
// gHeap.PushRoot(reinterpret_cast<RawObject**>(&L_));
}
~ListIter() {
// gHeap.PopRoot();
}
void Next() {
i_++;
}
bool Done() {
// "unsigned size_t was a mistake"
return i_ >= static_cast<int>(L_->len_);
}
T Value() {
return L_->slab_->items_[i_];
}
T iterNext() {
if (Done()) {
throw Alloc<StopIteration>();
}
T ret = L_->slab_->items_[i_];
Next();
return ret;
}
// only for use with generators
List<T>* GetList() {
return L_;
}
private:
List<T>* L_;
int i_;
};
// list(it) returns the iterator's backing list
template <typename T>
List<T>* list(ListIter<T> it) {
return list(it.GetList());
}
// TODO: Does using pointers rather than indices make this more efficient?
template <class T>
class ReverseListIter {
public:
explicit ReverseListIter(List<T>* L) : L_(L), i_(L_->len_ - 1) {
}
void Next() {
i_--;
}
bool Done() {
return i_ < 0;
}
T Value() {
return L_->slab_->items_[i_];
}
private:
List<T>* L_;
int i_;
};
int max(List<int>* elems);
#endif // MYCPP_GC_LIST_H