| ... | ... | @@ -0,0 +1,276 @@ |
| 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 | /// Note that the push() and pop() convenience methods perform a copy, but you can instead use |
| 70 | /// addOne(), at(), setCapacity(), and shrinkCapacity() to avoid copying items. |
| 71 | /// |
| 72 | /// This data structure has O(1) push and O(1) pop. |
| 73 | /// |
| 74 | /// It supports preallocated elements, making it especially well suited when the expected maximum |
| 75 | /// size is small. `prealloc_item_count` must be 0, or a power of 2. |
| 76 | pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type { |
| 77 | return struct { |
| 78 | const Self = this; |
| 79 | const prealloc_exp = blk: { |
| 80 | // we don't use the prealloc_exp constant when prealloc_item_count is 0. |
| 81 | assert(prealloc_item_count != 0); |
| 82 | |
| 83 | const value = std.math.log2_int(usize, prealloc_item_count); |
| 84 | assert((1 << value) == prealloc_item_count); // prealloc_item_count must be a power of 2 |
| 85 | break :blk @typeOf(1)(value); |
| 86 | }; |
| 87 | const ShelfIndex = std.math.Log2Int(usize); |
| 88 | |
| 89 | allocator: &Allocator, |
| 90 | len: usize, |
| 91 | prealloc_segment: [prealloc_item_count]T, |
| 92 | dynamic_segments: []&T, |
| 93 | |
| 94 | /// Deinitialize with `deinit` |
| 95 | pub fn init(allocator: &Allocator) Self { |
| 96 | return Self { |
| 97 | .allocator = allocator, |
| 98 | .len = 0, |
| 99 | .prealloc_segment = undefined, |
| 100 | .dynamic_segments = []&T{}, |
| 101 | }; |
| 102 | } |
| 103 | |
| 104 | pub fn deinit(self: &Self) void { |
| 105 | self.freeShelves(ShelfIndex(self.dynamic_segments.len), 0); |
| 106 | self.allocator.free(self.dynamic_segments); |
| 107 | *self = undefined; |
| 108 | } |
| 109 | |
| 110 | pub fn at(self: &Self, i: usize) &T { |
| 111 | assert(i < self.len); |
| 112 | return self.uncheckedAt(i); |
| 113 | } |
| 114 | |
| 115 | pub fn count(self: &const Self) usize { |
| 116 | return self.len; |
| 117 | } |
| 118 | |
| 119 | pub fn push(self: &Self, item: &const T) !void { |
| 120 | const new_item_ptr = try self.addOne(); |
| 121 | *new_item_ptr = *item; |
| 122 | } |
| 123 | |
| 124 | pub fn pushMany(self: &Self, items: []const T) !void { |
| 125 | for (items) |item| { |
| 126 | try self.push(item); |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | pub fn pop(self: &Self) ?T { |
| 131 | if (self.len == 0) |
| 132 | return null; |
| 133 | |
| 134 | const index = self.len - 1; |
| 135 | const result = *self.uncheckedAt(index); |
| 136 | self.len = index; |
| 137 | return result; |
| 138 | } |
| 139 | |
| 140 | pub fn addOne(self: &Self) !&T { |
| 141 | const new_length = self.len + 1; |
| 142 | try self.setCapacity(new_length); |
| 143 | const result = self.uncheckedAt(self.len); |
| 144 | self.len = new_length; |
| 145 | return result; |
| 146 | } |
| 147 | |
| 148 | pub fn setCapacity(self: &Self, new_capacity: usize) !void { |
| 149 | if (new_capacity <= prealloc_item_count) { |
| 150 | const len = ShelfIndex(self.dynamic_segments.len); |
| 151 | if (len == 0) return; |
| 152 | self.freeShelves(len, 0); |
| 153 | self.allocator.free(self.dynamic_segments); |
| 154 | self.dynamic_segments = []&T{}; |
| 155 | return; |
| 156 | } |
| 157 | |
| 158 | const new_cap_shelf_count = shelfCount(new_capacity); |
| 159 | const old_shelf_count = ShelfIndex(self.dynamic_segments.len); |
| 160 | if (new_cap_shelf_count > old_shelf_count) { |
| 161 | self.dynamic_segments = try self.allocator.realloc(&T, self.dynamic_segments, new_cap_shelf_count); |
| 162 | var i = old_shelf_count; |
| 163 | errdefer { |
| 164 | self.freeShelves(i, old_shelf_count); |
| 165 | self.dynamic_segments = self.allocator.shrink(&T, self.dynamic_segments, old_shelf_count); |
| 166 | } |
| 167 | while (i < new_cap_shelf_count) : (i += 1) { |
| 168 | self.dynamic_segments[i] = (try self.allocator.alloc(T, shelfSize(i))).ptr; |
| 169 | } |
| 170 | return; |
| 171 | } |
| 172 | if (new_cap_shelf_count == old_shelf_count) { |
| 173 | return; |
| 174 | } |
| 175 | self.freeShelves(old_shelf_count, new_cap_shelf_count); |
| 176 | self.dynamic_segments = self.allocator.shrink(&T, self.dynamic_segments, new_cap_shelf_count); |
| 177 | } |
| 178 | |
| 179 | pub fn shrinkCapacity(self: &Self, new_capacity: usize) void { |
| 180 | assert(new_capacity <= prealloc_item_count or shelfCount(new_capacity) <= self.dynamic_segments.len); |
| 181 | self.setCapacity(new_capacity) catch unreachable; |
| 182 | } |
| 183 | |
| 184 | pub fn uncheckedAt(self: &Self, index: usize) &T { |
| 185 | if (index < prealloc_item_count) { |
| 186 | return &self.prealloc_segment[index]; |
| 187 | } |
| 188 | const shelf_index = shelfIndex(index); |
| 189 | const box_index = boxIndex(index, shelf_index); |
| 190 | return &self.dynamic_segments[shelf_index][box_index]; |
| 191 | } |
| 192 | |
| 193 | fn shelfCount(box_count: usize) ShelfIndex { |
| 194 | if (prealloc_item_count == 0) { |
| 195 | return std.math.log2_int_ceil(usize, box_count + 1); |
| 196 | } |
| 197 | return std.math.log2_int_ceil(usize, box_count + prealloc_item_count) - prealloc_exp - 1; |
| 198 | } |
| 199 | |
| 200 | fn shelfSize(shelf_index: ShelfIndex) usize { |
| 201 | if (prealloc_item_count == 0) { |
| 202 | return usize(1) << shelf_index; |
| 203 | } |
| 204 | return usize(1) << (shelf_index + (prealloc_exp + 1)); |
| 205 | } |
| 206 | |
| 207 | fn shelfIndex(list_index: usize) ShelfIndex { |
| 208 | if (prealloc_item_count == 0) { |
| 209 | return std.math.log2_int(usize, list_index + 1); |
| 210 | } |
| 211 | return std.math.log2_int(usize, list_index + prealloc_item_count) - prealloc_exp - 1; |
| 212 | } |
| 213 | |
| 214 | fn boxIndex(list_index: usize, shelf_index: ShelfIndex) usize { |
| 215 | if (prealloc_item_count == 0) { |
| 216 | return (list_index + 1) - (usize(1) << shelf_index); |
| 217 | } |
| 218 | return list_index + prealloc_item_count - (usize(1) << ((prealloc_exp + 1) + shelf_index)); |
| 219 | } |
| 220 | |
| 221 | fn freeShelves(self: &Self, from_count: ShelfIndex, to_count: ShelfIndex) void { |
| 222 | var i = from_count; |
| 223 | while (i != to_count) { |
| 224 | i -= 1; |
| 225 | self.allocator.free(self.dynamic_segments[i][0..shelfSize(i)]); |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | }; |
| 230 | } |
| 231 | |
| 232 | test "std.SegmentedList" { |
| 233 | var da = std.heap.DirectAllocator.init(); |
| 234 | defer da.deinit(); |
| 235 | var a = &da.allocator; |
| 236 | |
| 237 | try testSegmentedList(0, a); |
| 238 | try testSegmentedList(1, a); |
| 239 | try testSegmentedList(2, a); |
| 240 | try testSegmentedList(4, a); |
| 241 | try testSegmentedList(8, a); |
| 242 | try testSegmentedList(16, a); |
| 243 | } |
| 244 | |
| 245 | fn testSegmentedList(comptime prealloc: usize, allocator: &Allocator) !void { |
| 246 | var list = SegmentedList(i32, prealloc).init(allocator); |
| 247 | defer list.deinit(); |
| 248 | |
| 249 | {var i: usize = 0; while (i < 100) : (i += 1) { |
| 250 | try list.push(i32(i + 1)); |
| 251 | assert(list.len == i + 1); |
| 252 | }} |
| 253 | |
| 254 | {var i: usize = 0; while (i < 100) : (i += 1) { |
| 255 | assert(*list.at(i) == i32(i + 1)); |
| 256 | }} |
| 257 | |
| 258 | assert(??list.pop() == 100); |
| 259 | assert(list.len == 99); |
| 260 | |
| 261 | try list.pushMany([]i32 { 1, 2, 3 }); |
| 262 | assert(list.len == 102); |
| 263 | assert(??list.pop() == 3); |
| 264 | assert(??list.pop() == 2); |
| 265 | assert(??list.pop() == 1); |
| 266 | assert(list.len == 99); |
| 267 | |
| 268 | try list.pushMany([]const i32 {}); |
| 269 | assert(list.len == 99); |
| 270 | |
| 271 | var i: i32 = 99; |
| 272 | while (list.pop()) |item| : (i -= 1) { |
| 273 | assert(item == i); |
| 274 | list.shrinkCapacity(list.len); |
| 275 | } |
| 276 | } |