| ... | ... | @@ -0,0 +1,272 @@ |
| 1 | const std = @import("index.zig"); |
| 2 | const assert = std.debug.assert; |
| 3 | const 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. |
| 74 | pub 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 | |
| 228 | test "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 | |
| 241 | fn 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 | } |