authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-05-07 01:04:43-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-05-07 01:04:43-04:00
log41e1cd185b82a518c58c92544c45f0348c03ef74
tree285d0d90e332dae78807c061cc01202b25c94229
parent4d6d2f1cd2a46e95b998b6bbc1effc72b2f4923c

std.SegmentedList implementation


5 files changed, 330 insertions(+), 34 deletions(-)

CMakeLists.txt+29-28
......@@ -416,8 +416,8 @@ set(ZIG_CPP_SOURCES
416416set(ZIG_STD_FILES
417417 "array_list.zig"
418418 "atomic/index.zig"
419 "atomic/stack.zig"
420419 "atomic/queue.zig"
420 "atomic/stack.zig"
421421 "base64.zig"
422422 "buf_map.zig"
423423 "buf_set.zig"
......@@ -427,13 +427,13 @@ set(ZIG_STD_FILES
427427 "c/index.zig"
428428 "c/linux.zig"
429429 "c/windows.zig"
430 "crypto/blake2.zig"
431 "crypto/hmac.zig"
430432 "crypto/index.zig"
431433 "crypto/md5.zig"
432434 "crypto/sha1.zig"
433435 "crypto/sha2.zig"
434436 "crypto/sha3.zig"
435 "crypto/blake2.zig"
436 "crypto/hmac.zig"
437437 "cstr.zig"
438438 "debug/failing_allocator.zig"
439439 "debug/index.zig"
......@@ -445,12 +445,12 @@ set(ZIG_STD_FILES
445445 "fmt/errol/index.zig"
446446 "fmt/errol/lookup.zig"
447447 "fmt/index.zig"
448 "hash_map.zig"
449 "hash/index.zig"
450448 "hash/adler.zig"
451449 "hash/crc.zig"
452450 "hash/fnv.zig"
451 "hash/index.zig"
453452 "hash/siphash.zig"
453 "hash_map.zig"
454454 "heap.zig"
455455 "index.zig"
456456 "io.zig"
......@@ -466,6 +466,28 @@ set(ZIG_STD_FILES
466466 "math/atanh.zig"
467467 "math/cbrt.zig"
468468 "math/ceil.zig"
469 "math/complex/abs.zig"
470 "math/complex/acos.zig"
471 "math/complex/acosh.zig"
472 "math/complex/arg.zig"
473 "math/complex/asin.zig"
474 "math/complex/asinh.zig"
475 "math/complex/atan.zig"
476 "math/complex/atanh.zig"
477 "math/complex/conj.zig"
478 "math/complex/cos.zig"
479 "math/complex/cosh.zig"
480 "math/complex/exp.zig"
481 "math/complex/index.zig"
482 "math/complex/ldexp.zig"
483 "math/complex/log.zig"
484 "math/complex/pow.zig"
485 "math/complex/proj.zig"
486 "math/complex/sin.zig"
487 "math/complex/sinh.zig"
488 "math/complex/sqrt.zig"
489 "math/complex/tan.zig"
490 "math/complex/tanh.zig"
469491 "math/copysign.zig"
470492 "math/cos.zig"
471493 "math/cosh.zig"
......@@ -502,33 +524,12 @@ set(ZIG_STD_FILES
502524 "math/tan.zig"
503525 "math/tanh.zig"
504526 "math/trunc.zig"
505 "math/complex/abs.zig"
506 "math/complex/acosh.zig"
507 "math/complex/acos.zig"
508 "math/complex/arg.zig"
509 "math/complex/asinh.zig"
510 "math/complex/asin.zig"
511 "math/complex/atanh.zig"
512 "math/complex/atan.zig"
513 "math/complex/conj.zig"
514 "math/complex/cosh.zig"
515 "math/complex/cos.zig"
516 "math/complex/exp.zig"
517 "math/complex/index.zig"
518 "math/complex/ldexp.zig"
519 "math/complex/log.zig"
520 "math/complex/pow.zig"
521 "math/complex/proj.zig"
522 "math/complex/sinh.zig"
523 "math/complex/sin.zig"
524 "math/complex/sqrt.zig"
525 "math/complex/tanh.zig"
526 "math/complex/tan.zig"
527527 "mem.zig"
528528 "net.zig"
529529 "os/child_process.zig"
530530 "os/darwin.zig"
531531 "os/darwin_errno.zig"
532 "os/epoch.zig"
532533 "os/file.zig"
533534 "os/get_user_id.zig"
534535 "os/index.zig"
......@@ -538,13 +539,13 @@ set(ZIG_STD_FILES
538539 "os/linux/x86_64.zig"
539540 "os/path.zig"
540541 "os/time.zig"
541 "os/epoch.zig"
542542 "os/windows/error.zig"
543543 "os/windows/index.zig"
544544 "os/windows/util.zig"
545545 "os/zen.zig"
546546 "rand/index.zig"
547547 "rand/ziggurat.zig"
548 "segmented_list.zig"
548549 "sort.zig"
549550 "special/bootstrap.zig"
550551 "special/bootstrap_lib.zig"
std/index.zig+2
......@@ -7,6 +7,7 @@ pub const BufferOutStream = @import("buffer.zig").BufferOutStream;
77pub const HashMap = @import("hash_map.zig").HashMap;
88pub const LinkedList = @import("linked_list.zig").LinkedList;
99pub const IntrusiveLinkedList = @import("linked_list.zig").IntrusiveLinkedList;
10pub const SegmentedList = @import("segmented_list.zig").SegmentedList;
1011
1112pub const atomic = @import("atomic/index.zig");
1213pub const base64 = @import("base64.zig");
......@@ -43,6 +44,7 @@ test "std" {
4344 _ = @import("buffer.zig");
4445 _ = @import("hash_map.zig");
4546 _ = @import("linked_list.zig");
47 _ = @import("segmented_list.zig");
4648
4749 _ = @import("base64.zig");
4850 _ = @import("build.zig");
std/math/index.zig+26
......@@ -558,6 +558,32 @@ test "math.floorPowerOfTwo" {
558558 comptime testFloorPowerOfTwo();
559559}
560560
561pub fn log2_int(comptime T: type, x: T) Log2Int(T) {
562 assert(x != 0);
563 return Log2Int(T)(T.bit_count - 1 - @clz(x));
564}
565
566pub fn log2_int_ceil(comptime T: type, x: T) Log2Int(T) {
567 assert(x != 0);
568 const log2_val = log2_int(T, x);
569 if (T(1) << log2_val == x)
570 return log2_val;
571 return log2_val + 1;
572}
573
574test "std.math.log2_int_ceil" {
575 assert(log2_int_ceil(u32, 1) == 0);
576 assert(log2_int_ceil(u32, 2) == 1);
577 assert(log2_int_ceil(u32, 3) == 2);
578 assert(log2_int_ceil(u32, 4) == 2);
579 assert(log2_int_ceil(u32, 5) == 3);
580 assert(log2_int_ceil(u32, 6) == 3);
581 assert(log2_int_ceil(u32, 7) == 3);
582 assert(log2_int_ceil(u32, 8) == 3);
583 assert(log2_int_ceil(u32, 9) == 4);
584 assert(log2_int_ceil(u32, 10) == 4);
585}
586
561587fn testFloorPowerOfTwo() void {
562588 assert(floorPowerOfTwo(u32, 63) == 32);
563589 assert(floorPowerOfTwo(u32, 64) == 64);
std/math/log2.zig+1-6
......@@ -31,17 +31,12 @@ pub fn log2(x: var) @typeOf(x) {
3131 return result;
3232 },
3333 TypeId.Int => {
34 return log2_int(T, x);
34 return math.log2_int(T, x);
3535 },
3636 else => @compileError("log2 not implemented for " ++ @typeName(T)),
3737 }
3838}
3939
40pub fn log2_int(comptime T: type, x: T) T {
41 assert(x != 0);
42 return T.bit_count - 1 - T(@clz(x));
43}
44
4540pub fn log2_32(x_: f32) f32 {
4641 const ivln2hi: f32 = 1.4428710938e+00;
4742 const ivln2lo: f32 = -1.7605285393e-04;
std/segmented_list.zig created+272
......@@ -0,0 +1,272 @@
1const std = @import("index.zig");
2const assert = std.debug.assert;
3const Allocator = std.mem.Allocator;
4
5// Imagine that `fn at(self: &Self, index: usize) &T` is a customer asking for a box
6// from a warehouse, based on a flat array, boxes ordered from 0 to N - 1.
7// But the warehouse actually stores boxes in shelves of increasing powers of 2 sizes.
8// So when the customer requests a box index, we have to translate it to shelf index
9// and box index within that shelf. Illustration:
10//
11// customer indexes:
12// shelf 0: 0
13// shelf 1: 1 2
14// shelf 2: 3 4 5 6
15// shelf 3: 7 8 9 10 11 12 13 14
16// shelf 4: 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
17// shelf 5: 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
18// ...
19//
20// warehouse indexes:
21// shelf 0: 0
22// shelf 1: 0 1
23// shelf 2: 0 1 2 3
24// shelf 3: 0 1 2 3 4 5 6 7
25// shelf 4: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
26// shelf 5: 0 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
27// ...
28//
29// With this arrangement, here are the equations to get the shelf index and
30// box index based on customer box index:
31//
32// shelf_index = floor(log2(customer_index + 1))
33// shelf_count = ceil(log2(box_count + 1))
34// box_index = customer_index + 1 - 2 ** shelf
35// shelf_size = 2 ** shelf_index
36//
37// Now we complicate it a little bit further by adding a preallocated shelf, which must be
38// a power of 2:
39// prealloc=4
40//
41// customer indexes:
42// prealloc: 0 1 2 3
43// shelf 0: 4 5 6 7 8 9 10 11
44// shelf 1: 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
45// shelf 2: 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
46// ...
47//
48// warehouse indexes:
49// prealloc: 0 1 2 3
50// shelf 0: 0 1 2 3 4 5 6 7
51// shelf 1: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
52// shelf 2: 0 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
53// ...
54//
55// Now the equations are:
56//
57// shelf_index = floor(log2(customer_index + prealloc)) - log2(prealloc) - 1
58// shelf_count = ceil(log2(box_count + prealloc)) - log2(prealloc) - 1
59// box_index = customer_index + prealloc - 2 ** (log2(prealloc) + 1 + shelf)
60// shelf_size = prealloc * 2 ** (shelf_index + 1)
61
62/// This is a stack data structure where pointers to indexes have the same lifetime as the data structure
63/// itself, unlike ArrayList where push() invalidates all existing element pointers.
64/// The tradeoff is that elements are not guaranteed to be contiguous. For that, use ArrayList.
65/// Note however that most elements are contiguous, making this data structure cache-friendly.
66///
67/// Because it never has to copy elements from an old location to a new location, it does not require
68/// its elements to be copyable, and it avoids wasting memory when backed by an ArenaAllocator.
69///
70/// This data structure has O(1) push and O(1) pop.
71///
72/// It supports preallocated elements, making it especially well suited when the expected maximum
73/// size is small. `prealloc_item_count` must be 0, or a power of 2.
74pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type {
75 return struct {
76 const Self = this;
77 const prealloc_base = blk: {
78 assert(prealloc_item_count != 0);
79 const value = std.math.log2_int(usize, prealloc_item_count);
80 assert((1 << value) == prealloc_item_count); // prealloc_item_count must be a power of 2
81 break :blk @typeOf(1)(value);
82 };
83 const ShelfIndex = std.math.Log2Int(usize);
84
85 allocator: &Allocator,
86 len: usize,
87 prealloc_segment: [prealloc_item_count]T,
88 dynamic_segments: []&T,
89
90 /// Deinitialize with `deinit`
91 pub fn init(allocator: &Allocator) Self {
92 return Self {
93 .allocator = allocator,
94 .len = 0,
95 .prealloc_segment = undefined,
96 .dynamic_segments = []&T{},
97 };
98 }
99
100 pub fn deinit(self: &Self) void {
101 self.freeShelves(ShelfIndex(self.dynamic_segments.len), 0);
102 self.allocator.free(self.dynamic_segments);
103 *self = undefined;
104 }
105
106 pub fn at(self: &Self, i: usize) &T {
107 assert(i < self.len);
108 return self.uncheckedAt(i);
109 }
110
111 pub fn count(self: &const Self) usize {
112 return self.len;
113 }
114
115 pub fn push(self: &Self, item: &const T) !void {
116 const new_item_ptr = try self.addOne();
117 *new_item_ptr = *item;
118 }
119
120 pub fn pushMany(self: &Self, items: []const T) !void {
121 for (items) |item| {
122 try self.push(item);
123 }
124 }
125
126 pub fn pop(self: &Self) ?T {
127 if (self.len == 0)
128 return null;
129
130 const index = self.len - 1;
131 const result = *self.uncheckedAt(index);
132 self.len = index;
133 return result;
134 }
135
136 pub fn addOne(self: &Self) !&T {
137 const new_length = self.len + 1;
138 try self.setCapacity(new_length);
139 const result = self.uncheckedAt(self.len);
140 self.len = new_length;
141 return result;
142 }
143
144 pub fn setCapacity(self: &Self, new_capacity: usize) !void {
145 if (new_capacity <= prealloc_item_count) {
146 const len = ShelfIndex(self.dynamic_segments.len);
147 if (len == 0) return;
148 self.freeShelves(len, 0);
149 self.allocator.free(self.dynamic_segments);
150 self.dynamic_segments = []&T{};
151 return;
152 }
153
154 const new_cap_shelf_count = shelfCount(new_capacity);
155 const old_shelf_count = ShelfIndex(self.dynamic_segments.len);
156 if (new_cap_shelf_count > old_shelf_count) {
157 self.dynamic_segments = try self.allocator.realloc(&T, self.dynamic_segments, new_cap_shelf_count);
158 var i = old_shelf_count;
159 errdefer {
160 self.freeShelves(i, old_shelf_count);
161 self.dynamic_segments = self.allocator.shrink(&T, self.dynamic_segments, old_shelf_count);
162 }
163 while (i < new_cap_shelf_count) : (i += 1) {
164 self.dynamic_segments[i] = (try self.allocator.alloc(T, shelfSize(i))).ptr;
165 }
166 return;
167 }
168 if (new_cap_shelf_count == old_shelf_count) {
169 return;
170 }
171 self.freeShelves(old_shelf_count, new_cap_shelf_count);
172 self.dynamic_segments = self.allocator.shrink(&T, self.dynamic_segments, new_cap_shelf_count);
173 }
174
175 pub fn shrinkCapacity(self: &Self, new_capacity: usize) void {
176 assert(new_capacity <= prealloc_item_count or shelfCount(new_capacity) <= self.dynamic_segments.len);
177 self.setCapacity(new_capacity) catch unreachable;
178 }
179
180 pub fn uncheckedAt(self: &Self, index: usize) &T {
181 if (index < prealloc_item_count) {
182 return &self.prealloc_segment[index];
183 }
184 const shelf_index = shelfIndex(index);
185 const box_index = boxIndex(index, shelf_index);
186 return &self.dynamic_segments[shelf_index][box_index];
187 }
188
189 fn shelfCount(box_count: usize) ShelfIndex {
190 if (prealloc_item_count == 0) {
191 return std.math.log2_int_ceil(usize, box_count + 1);
192 }
193 return std.math.log2_int_ceil(usize, box_count + prealloc_item_count) - prealloc_base - 1;
194 }
195
196 fn shelfSize(shelf_index: ShelfIndex) usize {
197 if (prealloc_item_count == 0) {
198 return usize(1) << shelf_index;
199 }
200 return usize(1) << (shelf_index + (prealloc_base + 1));
201 }
202
203 fn shelfIndex(list_index: usize) ShelfIndex {
204 if (prealloc_item_count == 0) {
205 return std.math.log2_int(usize, list_index + 1);
206 }
207 return std.math.log2_int(usize, list_index + prealloc_item_count) - prealloc_base - 1;
208 }
209
210 fn boxIndex(list_index: usize, shelf_index: ShelfIndex) usize {
211 if (prealloc_item_count == 0) {
212 return (list_index + 1) - (usize(1) << shelf_index);
213 }
214 return list_index + prealloc_item_count - (usize(1) << ((prealloc_base + 1) + shelf_index));
215 }
216
217 fn freeShelves(self: &Self, from_count: ShelfIndex, to_count: ShelfIndex) void {
218 var i = from_count;
219 while (i != to_count) {
220 i -= 1;
221 self.allocator.free(self.dynamic_segments[i][0..shelfSize(i)]);
222 }
223 }
224
225 };
226}
227
228test "std.SegmentedList" {
229 var da = std.heap.DirectAllocator.init();
230 defer da.deinit();
231 var a = &da.allocator;
232
233 try testSegmentedList(0, a);
234 try testSegmentedList(1, a);
235 try testSegmentedList(2, a);
236 try testSegmentedList(4, a);
237 try testSegmentedList(8, a);
238 try testSegmentedList(16, a);
239}
240
241fn testSegmentedList(comptime prealloc: usize, allocator: &Allocator) !void {
242 var list = SegmentedList(i32, prealloc).init(allocator);
243 defer list.deinit();
244
245 {var i: usize = 0; while (i < 100) : (i += 1) {
246 try list.push(i32(i + 1));
247 assert(list.len == i + 1);
248 }}
249
250 {var i: usize = 0; while (i < 100) : (i += 1) {
251 assert(*list.at(i) == i32(i + 1));
252 }}
253
254 assert(??list.pop() == 100);
255 assert(list.len == 99);
256
257 try list.pushMany([]i32 { 1, 2, 3 });
258 assert(list.len == 102);
259 assert(??list.pop() == 3);
260 assert(??list.pop() == 2);
261 assert(??list.pop() == 1);
262 assert(list.len == 99);
263
264 try list.pushMany([]const i32 {});
265 assert(list.len == 99);
266
267 var i: i32 = 99;
268 while (list.pop()) |item| : (i -= 1) {
269 assert(item == i);
270 list.shrinkCapacity(list.len);
271 }
272}