| ... | @@ -0,0 +1,642 @@ |
| 1 | //! This allocator takes an existing allocator, wraps it, and provides an interface where |
| 2 | //! you can allocate and then free it all together. Calls to free an individual item only |
| 3 | //! free the item if it was the most recent allocation, otherwise calls to free do |
| 4 | //! nothing. |
| 5 | //! |
| 6 | //! The `Allocator` implementation provided is threadsafe, given that `child_allocator` |
| 7 | //! is threadsafe as well. |
| 8 | const ArenaAllocator = @This(); |
| 9 | |
| 10 | child_allocator: Allocator, |
| 11 | state: State, |
| 12 | |
| 13 | /// Inner state of ArenaAllocator. Can be stored rather than the entire ArenaAllocator |
| 14 | /// as a memory-saving optimization. |
| 15 | /// |
| 16 | /// Default initialization of this struct is deprecated; use `init` instead. |
| 17 | pub const State = struct { |
| 18 | used_list: ?*Node = null, |
| 19 | free_list: ?*Node = null, |
| 20 | |
| 21 | pub const init: State = .{ |
| 22 | .used_list = null, |
| 23 | .free_list = null, |
| 24 | }; |
| 25 | |
| 26 | pub fn promote(state: State, child_allocator: Allocator) ArenaAllocator { |
| 27 | return .{ |
| 28 | .child_allocator = child_allocator, |
| 29 | .state = state, |
| 30 | }; |
| 31 | } |
| 32 | }; |
| 33 | |
| 34 | pub fn allocator(arena: *ArenaAllocator) Allocator { |
| 35 | return .{ |
| 36 | .ptr = arena, |
| 37 | .vtable = &.{ |
| 38 | .alloc = alloc, |
| 39 | .resize = resize, |
| 40 | .remap = remap, |
| 41 | .free = free, |
| 42 | }, |
| 43 | }; |
| 44 | } |
| 45 | |
| 46 | pub fn init(child_allocator: Allocator) ArenaAllocator { |
| 47 | return State.init.promote(child_allocator); |
| 48 | } |
| 49 | |
| 50 | /// Not threadsafe. |
| 51 | pub fn deinit(arena: ArenaAllocator) void { |
| 52 | // NOTE: When changing this, make sure `reset()` is adjusted accordingly! |
| 53 | |
| 54 | for ([_]?*Node{ arena.state.used_list, arena.state.free_list }) |first_node| { |
| 55 | var it = first_node; |
| 56 | while (it) |node| { |
| 57 | // this has to occur before the free because the free frees node |
| 58 | it = node.next; |
| 59 | arena.child_allocator.rawFree(node.allocatedSliceUnsafe(), .of(Node), @returnAddress()); |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | /// Queries the current memory use of this arena. |
| 65 | /// This will **not** include the storage required for internal keeping. |
| 66 | /// |
| 67 | /// Not threadsafe. |
| 68 | pub fn queryCapacity(arena: ArenaAllocator) usize { |
| 69 | var capacity: usize = 0; |
| 70 | for ([_]?*Node{ arena.state.used_list, arena.state.free_list }) |first_node| { |
| 71 | capacity += countListCapacity(first_node); |
| 72 | } |
| 73 | return capacity; |
| 74 | } |
| 75 | fn countListCapacity(first_node: ?*Node) usize { |
| 76 | var capacity: usize = 0; |
| 77 | var it = first_node; |
| 78 | while (it) |node| : (it = node.next) { |
| 79 | // Compute the actually allocated size excluding the |
| 80 | // linked list node. |
| 81 | capacity += node.size - @sizeOf(Node); |
| 82 | } |
| 83 | return capacity; |
| 84 | } |
| 85 | |
| 86 | pub const ResetMode = union(enum) { |
| 87 | /// Releases all allocated memory in the arena. |
| 88 | free_all, |
| 89 | /// This will pre-heat the arena for future allocations by allocating a |
| 90 | /// large enough buffer for all previously done allocations. |
| 91 | /// Preheating will speed up the allocation process by invoking the backing allocator |
| 92 | /// less often than before. If `reset()` is used in a loop, this means that after the |
| 93 | /// biggest operation, no memory allocations are performed anymore. |
| 94 | retain_capacity, |
| 95 | /// This is the same as `retain_capacity`, but the memory will be shrunk to |
| 96 | /// this value if it exceeds the limit. |
| 97 | retain_with_limit: usize, |
| 98 | }; |
| 99 | /// Resets the arena allocator and frees all allocated memory. |
| 100 | /// |
| 101 | /// `mode` defines how the currently allocated memory is handled. |
| 102 | /// See the variant documentation for `ResetMode` for the effects of each mode. |
| 103 | /// |
| 104 | /// The function will return whether the reset operation was successful or not. |
| 105 | /// If the reallocation failed `false` is returned. The arena will still be fully |
| 106 | /// functional in that case, all memory is released. Future allocations just might |
| 107 | /// be slower. |
| 108 | /// |
| 109 | /// Not threadsafe. |
| 110 | /// |
| 111 | /// NOTE: If `mode` is `free_all`, the function will always return `true`. |
| 112 | pub fn reset(arena: *ArenaAllocator, mode: ResetMode) bool { |
| 113 | // Some words on the implementation: |
| 114 | // The reset function can be implemented with two basic approaches: |
| 115 | // - Counting how much bytes were allocated since the last reset, and storing that |
| 116 | // information in State. This will make reset fast and alloc only a teeny tiny bit |
| 117 | // slower. |
| 118 | // - Counting how much bytes were allocated by iterating the chunk linked list. This |
| 119 | // will make reset slower, but alloc() keeps the same speed when reset() as if reset() |
| 120 | // would not exist. |
| 121 | // |
| 122 | // The second variant was chosen for implementation, as with more and more calls to reset(), |
| 123 | // the function will get faster and faster. At one point, the complexity of the function |
| 124 | // will drop to amortized O(1), as we're only ever having a single chunk that will not be |
| 125 | // reallocated, and we're not even touching the backing allocator anymore. |
| 126 | // |
| 127 | // Thus, only the first hand full of calls to reset() will actually need to iterate the linked |
| 128 | // list, all future calls are just taking the first node, and only resetting the `end_index` |
| 129 | // value. |
| 130 | |
| 131 | const limit: ?usize = switch (mode) { |
| 132 | .retain_capacity => null, |
| 133 | .retain_with_limit => |limit| limit, |
| 134 | .free_all => 0, |
| 135 | }; |
| 136 | if (limit == 0) { |
| 137 | // just reset when we don't have anything to reallocate |
| 138 | arena.deinit(); |
| 139 | arena.state = .init; |
| 140 | return true; |
| 141 | } |
| 142 | |
| 143 | const used_capacity = countListCapacity(arena.state.used_list); |
| 144 | const free_capacity = countListCapacity(arena.state.free_list); |
| 145 | |
| 146 | const new_used_capacity = if (limit) |lim| @min(lim, used_capacity) else used_capacity; |
| 147 | const new_free_capacity = if (limit) |lim| @min(lim - new_used_capacity, free_capacity) else free_capacity; |
| 148 | |
| 149 | var ok = true; |
| 150 | |
| 151 | for ( |
| 152 | [_]*?*Node{ &arena.state.used_list, &arena.state.free_list }, |
| 153 | [_]usize{ new_used_capacity, new_free_capacity }, |
| 154 | ) |first_node_ptr, new_capacity| { |
| 155 | // Free all nodes except for the last one |
| 156 | var it = first_node_ptr.*; |
| 157 | const node: *Node = while (it) |node| { |
| 158 | // this has to occur before the free because the free frees node |
| 159 | it = node.next; |
| 160 | if (it == null) break node; |
| 161 | arena.child_allocator.rawFree(node.allocatedSliceUnsafe(), .of(Node), @returnAddress()); |
| 162 | } else { |
| 163 | continue; |
| 164 | }; |
| 165 | const allocated_slice = node.allocatedSliceUnsafe(); |
| 166 | |
| 167 | if (new_capacity == 0) { |
| 168 | arena.child_allocator.rawFree(allocated_slice, .of(Node), @returnAddress()); |
| 169 | first_node_ptr.* = null; |
| 170 | continue; |
| 171 | } |
| 172 | |
| 173 | node.end_index = 0; |
| 174 | first_node_ptr.* = node; |
| 175 | |
| 176 | const adjusted_capacity: usize = mem.alignForward(usize, new_capacity, 2); |
| 177 | |
| 178 | if (allocated_slice.len - @sizeOf(Node) == adjusted_capacity) { |
| 179 | // perfect, no need to invoke the child_allocator |
| 180 | continue; |
| 181 | } |
| 182 | |
| 183 | if (arena.child_allocator.rawResize(allocated_slice, .of(Node), adjusted_capacity, @returnAddress())) { |
| 184 | // successful resize |
| 185 | node.size = adjusted_capacity; |
| 186 | } else { |
| 187 | // manual realloc |
| 188 | const new_ptr = arena.child_allocator.rawAlloc(adjusted_capacity, .of(Node), @returnAddress()) orelse { |
| 189 | // we failed to preheat the arena properly, signal this to the user. |
| 190 | ok = false; |
| 191 | continue; |
| 192 | }; |
| 193 | arena.child_allocator.rawFree(allocated_slice, .of(Node), @returnAddress()); |
| 194 | const new_first_node: *Node = @ptrCast(@alignCast(new_ptr)); |
| 195 | new_first_node.* = .{ |
| 196 | .size = adjusted_capacity, |
| 197 | .end_index = 0, |
| 198 | .next = null, |
| 199 | }; |
| 200 | first_node_ptr.* = new_first_node; |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | return ok; |
| 205 | } |
| 206 | |
| 207 | /// Concurrent accesses to node pointers generally have to have acquire/release |
| 208 | /// semantics to guarantee that newly allocated notes are in a valid state when |
| 209 | /// being inserted into a list. Exceptions are possible, e.g. a CAS loop that |
| 210 | /// never accesses the node returned on failure can use monotonic semantics on |
| 211 | /// failure, but must still use release semantics on success to protect the node |
| 212 | /// it's trying to push. |
| 213 | const Node = struct { |
| 214 | /// Only meant to be accessed indirectly via the methods supplied by this type, |
| 215 | /// except if the node is owned by the thread accessing it. |
| 216 | /// Must always be an even number to accomodate `resize_bit`. |
| 217 | size: usize, |
| 218 | /// Concurrent accesses to `end_index` can be monotonic since it is only ever |
| 219 | /// incremented in `alloc` and `resize` after being compared to `size`. |
| 220 | /// Since `size` can only grow and never shrink, memory access depending on |
| 221 | /// `end_index` can never be OOB. |
| 222 | end_index: usize, |
| 223 | /// This field should only be accessed if the node is owned by the thread |
| 224 | /// accessing it. |
| 225 | next: ?*Node, |
| 226 | |
| 227 | const resize_bit: usize = 1; |
| 228 | |
| 229 | fn loadEndIndex(node: *Node) usize { |
| 230 | return @atomicLoad(usize, &node.end_index, .monotonic); |
| 231 | } |
| 232 | |
| 233 | /// Returns `null` on success and previous value on failure. |
| 234 | fn trySetEndIndex(node: *Node, from: usize, to: usize) ?usize { |
| 235 | assert(from != to); // check this before attempting to set `end_index`! |
| 236 | return @cmpxchgWeak(usize, &node.end_index, from, to, .monotonic, .monotonic); |
| 237 | } |
| 238 | |
| 239 | fn loadBuf(node: *Node) []u8 { |
| 240 | // monotonic is fine since `size` can only ever grow, so the buffer returned |
| 241 | // by this function is always valid memory. |
| 242 | const size = @atomicLoad(usize, &node.size, .monotonic); |
| 243 | return @as([*]u8, @ptrCast(node))[0 .. size & ~resize_bit][@sizeOf(Node)..]; |
| 244 | } |
| 245 | |
| 246 | /// Returns allocated slice or `null` if node is already (being) resized. |
| 247 | fn beginResize(node: *Node) ?[]u8 { |
| 248 | const size = @atomicRmw(usize, &node.size, .Or, resize_bit, .acquire); // syncs with release in `endResize` |
| 249 | if (size & resize_bit != 0) return null; |
| 250 | return @as([*]u8, @ptrCast(node))[0..size]; |
| 251 | } |
| 252 | |
| 253 | fn endResize(node: *Node, size: usize) void { |
| 254 | assert(size & resize_bit == 0); |
| 255 | return @atomicStore(usize, &node.size, size, .release); // syncs with acquire in `beginResize` |
| 256 | } |
| 257 | |
| 258 | /// Not threadsafe. |
| 259 | fn allocatedSliceUnsafe(node: *Node) []u8 { |
| 260 | return @as([*]u8, @ptrCast(node))[0 .. node.size & ~resize_bit]; |
| 261 | } |
| 262 | }; |
| 263 | |
| 264 | fn loadFirstNode(arena: *ArenaAllocator) ?*Node { |
| 265 | return @atomicLoad(?*Node, &arena.state.used_list, .acquire); // syncs with release in successful `tryPushNode` |
| 266 | } |
| 267 | |
| 268 | const PushResult = union(enum) { |
| 269 | success, |
| 270 | failure: ?*Node, |
| 271 | }; |
| 272 | fn tryPushNode(arena: *ArenaAllocator, node: *Node) PushResult { |
| 273 | assert(node != node.next); |
| 274 | if (@cmpxchgStrong( // strong because retrying means discarding a fitting node -> expensive |
| 275 | ?*Node, |
| 276 | &arena.state.used_list, |
| 277 | node.next, |
| 278 | node, |
| 279 | .release, // syncs with acquire in failure path or `loadFirstNode` |
| 280 | .acquire, // syncs with release in success path |
| 281 | )) |old_node| { |
| 282 | return .{ .failure = old_node }; |
| 283 | } else { |
| 284 | return .success; |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | fn stealFreeList(arena: *ArenaAllocator) ?*Node { |
| 289 | // syncs with acq_rel in other `stealFreeList` calls or release in `pushFreeList` |
| 290 | return @atomicRmw(?*Node, &arena.state.free_list, .Xchg, null, .acq_rel); |
| 291 | } |
| 292 | |
| 293 | fn pushFreeList(arena: *ArenaAllocator, first: *Node, last: *Node) void { |
| 294 | assert(first != last.next); |
| 295 | while (@cmpxchgWeak( |
| 296 | ?*Node, |
| 297 | &arena.state.free_list, |
| 298 | last.next, |
| 299 | first, |
| 300 | .release, // syncs with acquire part of acq_rel in `stealFreeList` |
| 301 | .monotonic, // we never access any fields of `old_free_list`, we only care about the pointer |
| 302 | )) |old_free_list| { |
| 303 | last.next = old_free_list; |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | fn alignedIndex(buf_ptr: [*]u8, end_index: usize, alignment: Alignment) usize { |
| 308 | return end_index + |
| 309 | mem.alignPointerOffset(buf_ptr + end_index, alignment.toByteUnits()).?; |
| 310 | } |
| 311 | |
| 312 | fn alloc(ctx: *anyopaque, n: usize, alignment: Alignment, ret_addr: usize) ?[*]u8 { |
| 313 | const arena: *ArenaAllocator = @ptrCast(@alignCast(ctx)); |
| 314 | _ = ret_addr; |
| 315 | |
| 316 | assert(n > 0); |
| 317 | |
| 318 | var cur_first_node = arena.loadFirstNode(); |
| 319 | |
| 320 | var cur_new_node: ?*Node = null; |
| 321 | defer if (cur_new_node) |node| { |
| 322 | node.next = null; // optimize for empty free list |
| 323 | arena.pushFreeList(node, node); |
| 324 | }; |
| 325 | |
| 326 | retry: while (true) { |
| 327 | const first_node: ?*Node, const prev_size: usize = first_node: { |
| 328 | const node = cur_first_node orelse break :first_node .{ null, 0 }; |
| 329 | var end_index = node.loadEndIndex(); |
| 330 | while (true) { |
| 331 | const buf = node.loadBuf(); |
| 332 | const aligned_index = alignedIndex(buf.ptr, end_index, alignment); |
| 333 | |
| 334 | if (aligned_index + n > buf.len) { |
| 335 | break :first_node .{ node, buf.len }; |
| 336 | } |
| 337 | |
| 338 | end_index = node.trySetEndIndex(end_index, aligned_index + n) orelse { |
| 339 | return buf[aligned_index..][0..n].ptr; |
| 340 | }; |
| 341 | } |
| 342 | }; |
| 343 | |
| 344 | resize: { |
| 345 | // Before attempting to get our hands on a new node, we try to resize |
| 346 | // the one we're currently holding. This is an exclusive operation; |
| 347 | // if another thread is already in this section we can never resize. |
| 348 | |
| 349 | const node = first_node orelse break :resize; |
| 350 | const allocated_slice = node.beginResize() orelse break :resize; |
| 351 | var size = allocated_slice.len; |
| 352 | defer node.endResize(size); |
| 353 | |
| 354 | const buf = allocated_slice[@sizeOf(Node)..]; |
| 355 | const end_index = node.loadEndIndex(); |
| 356 | const aligned_index = alignedIndex(buf.ptr, end_index, alignment); |
| 357 | const new_size = mem.alignForward(usize, @sizeOf(Node) + aligned_index + n, 2); |
| 358 | |
| 359 | if (new_size <= allocated_slice.len) { |
| 360 | // a `resize` or `free` call managed to sneak in and we need to |
| 361 | // guarantee that `size` is only ever increased; retry! |
| 362 | continue :retry; |
| 363 | } |
| 364 | |
| 365 | if (arena.child_allocator.rawResize(allocated_slice, .of(Node), new_size, @returnAddress())) { |
| 366 | size = new_size; |
| 367 | |
| 368 | if (@cmpxchgStrong( // strong because a spurious failure could result in suboptimal usage of this node |
| 369 | usize, |
| 370 | &node.end_index, |
| 371 | end_index, |
| 372 | aligned_index + n, |
| 373 | .monotonic, |
| 374 | .monotonic, |
| 375 | ) == null) { |
| 376 | const new_buf = allocated_slice.ptr[0..new_size][@sizeOf(Node)..]; |
| 377 | return new_buf[aligned_index..][0..n].ptr; |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | // We need a new node! First, we search `free_list` for one that's big |
| 383 | // enough, if we don't find one there we fall back to allocating a new |
| 384 | // node with `child_allocator` (if we haven't already done that!). |
| 385 | |
| 386 | from_free_list: { |
| 387 | // We 'steal' the entire free list to operate on it without other |
| 388 | // threads getting up into our business. |
| 389 | // This is a rather pragmatic approach, but since the free list isn't |
| 390 | // used very frequently it's fine performance-wise, even under load. |
| 391 | // Also this avoids the ABA problem; stealing the list with an atomic |
| 392 | // swap doesn't introduce any potentially stale `next` pointers. |
| 393 | |
| 394 | const free_list = arena.stealFreeList(); |
| 395 | var first_free: ?*Node = free_list; |
| 396 | var last_free: ?*Node = free_list; |
| 397 | defer { |
| 398 | // Push remaining stolen free list back onto `arena.state.free_list`. |
| 399 | if (first_free) |first| { |
| 400 | const last = last_free.?; |
| 401 | assert(last.next == null); // optimize for no new nodes added during steal |
| 402 | arena.pushFreeList(first, last); |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | var best_fit_prev: ?*Node = null; |
| 407 | var best_fit: ?*Node = null; |
| 408 | var best_fit_diff: usize = std.math.maxInt(usize); |
| 409 | |
| 410 | var it_prev: ?*Node = null; |
| 411 | var it = free_list; |
| 412 | const candidate: ?*Node, const prev: ?*Node = find: while (it) |node| : ({ |
| 413 | it_prev = it; |
| 414 | it = node.next; |
| 415 | }) { |
| 416 | last_free = node; |
| 417 | assert(node.size & Node.resize_bit == 0); |
| 418 | const buf = node.allocatedSliceUnsafe()[@sizeOf(Node)..]; |
| 419 | const aligned_index = alignedIndex(buf.ptr, 0, alignment); |
| 420 | if (buf.len < aligned_index + n) { |
| 421 | const diff = aligned_index + n - buf.len; |
| 422 | if (diff <= best_fit_diff) { |
| 423 | best_fit_prev = it_prev; |
| 424 | best_fit = node; |
| 425 | best_fit_diff = diff; |
| 426 | } |
| 427 | continue :find; |
| 428 | } |
| 429 | break :find .{ node, it_prev }; |
| 430 | } else { |
| 431 | // Ideally we want to use all nodes in `free_list` eventually, |
| 432 | // so even if none fit we'll try to resize the one that was the |
| 433 | // closest to being large enough. |
| 434 | if (best_fit) |node| { |
| 435 | const allocated_slice = node.allocatedSliceUnsafe(); |
| 436 | const buf = allocated_slice[@sizeOf(Node)..]; |
| 437 | const aligned_index = alignedIndex(buf.ptr, 0, alignment); |
| 438 | const new_size = mem.alignForward(usize, @sizeOf(Node) + aligned_index + n, 2); |
| 439 | |
| 440 | if (arena.child_allocator.rawResize(allocated_slice, .of(Node), new_size, @returnAddress())) { |
| 441 | node.size = new_size; |
| 442 | break :find .{ node, best_fit_prev }; |
| 443 | } |
| 444 | } |
| 445 | break :from_free_list; |
| 446 | }; |
| 447 | |
| 448 | it = last_free; |
| 449 | while (it) |node| : (it = node.next) { |
| 450 | last_free = node; |
| 451 | } |
| 452 | |
| 453 | const node = candidate orelse break :from_free_list; |
| 454 | |
| 455 | const old_next = node.next; |
| 456 | |
| 457 | const buf = node.allocatedSliceUnsafe()[@sizeOf(Node)..]; |
| 458 | const aligned_index = alignedIndex(buf.ptr, 0, alignment); |
| 459 | |
| 460 | node.end_index = aligned_index + n; |
| 461 | node.next = first_node; |
| 462 | |
| 463 | switch (arena.tryPushNode(node)) { |
| 464 | .success => { |
| 465 | // finish removing node from free list |
| 466 | if (prev) |p| p.next = old_next; |
| 467 | if (node == first_free) first_free = old_next; |
| 468 | if (node == last_free) last_free = prev; |
| 469 | return buf[aligned_index..][0..n].ptr; |
| 470 | }, |
| 471 | .failure => |old_first_node| { |
| 472 | cur_first_node = old_first_node; |
| 473 | // restore free list to as we found it |
| 474 | node.next = old_next; |
| 475 | continue :retry; |
| 476 | }, |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | const new_node: *Node = new_node: { |
| 481 | if (cur_new_node) |new_node| { |
| 482 | break :new_node new_node; |
| 483 | } else { |
| 484 | @branchHint(.cold); |
| 485 | } |
| 486 | |
| 487 | const size: usize = size: { |
| 488 | const min_size = @sizeOf(Node) + alignment.toByteUnits() + n; |
| 489 | const big_enough_size = prev_size + min_size + 16; |
| 490 | break :size mem.alignForward(usize, big_enough_size + big_enough_size / 2, 2); |
| 491 | }; |
| 492 | assert(size & Node.resize_bit == 0); |
| 493 | const ptr = arena.child_allocator.rawAlloc(size, .of(Node), @returnAddress()) orelse |
| 494 | return null; |
| 495 | const new_node: *Node = @ptrCast(@alignCast(ptr)); |
| 496 | new_node.* = .{ |
| 497 | .size = size, |
| 498 | .end_index = undefined, // set below |
| 499 | .next = undefined, // set below |
| 500 | }; |
| 501 | cur_new_node = new_node; |
| 502 | break :new_node new_node; |
| 503 | }; |
| 504 | |
| 505 | const buf = new_node.allocatedSliceUnsafe()[@sizeOf(Node)..]; |
| 506 | const aligned_index = alignedIndex(buf.ptr, 0, alignment); |
| 507 | assert(new_node.size >= @sizeOf(Node) + aligned_index + n); |
| 508 | |
| 509 | new_node.end_index = aligned_index + n; |
| 510 | new_node.next = first_node; |
| 511 | |
| 512 | switch (arena.tryPushNode(new_node)) { |
| 513 | .success => { |
| 514 | cur_new_node = null; |
| 515 | return buf[aligned_index..][0..n].ptr; |
| 516 | }, |
| 517 | .failure => |old_first_node| { |
| 518 | cur_first_node = old_first_node; |
| 519 | }, |
| 520 | } |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | fn resize(ctx: *anyopaque, buf: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) bool { |
| 525 | const arena: *ArenaAllocator = @ptrCast(@alignCast(ctx)); |
| 526 | _ = alignment; |
| 527 | _ = ret_addr; |
| 528 | |
| 529 | assert(buf.len > 0); |
| 530 | assert(new_len > 0); |
| 531 | if (buf.len == new_len) return true; |
| 532 | |
| 533 | const node = arena.loadFirstNode().?; |
| 534 | const cur_buf_ptr = @as([*]u8, @ptrCast(node)) + @sizeOf(Node); |
| 535 | |
| 536 | var cur_end_index = node.loadEndIndex(); |
| 537 | while (true) { |
| 538 | if (cur_buf_ptr + cur_end_index != buf.ptr + buf.len) { |
| 539 | // It's not the most recent allocation, so it cannot be expanded, |
| 540 | // but it's fine if they want to make it smaller. |
| 541 | return new_len <= buf.len; |
| 542 | } |
| 543 | |
| 544 | const new_end_index: usize = new_end_index: { |
| 545 | if (buf.len >= new_len) { |
| 546 | break :new_end_index cur_end_index - (buf.len - new_len); |
| 547 | } |
| 548 | const cur_buf_len: usize = node.loadBuf().len; |
| 549 | // Saturating arithmetic because `end_index` and `size` are not |
| 550 | // guaranteed to be in sync. |
| 551 | if (cur_buf_len -| cur_end_index >= new_len - buf.len) { |
| 552 | break :new_end_index cur_end_index + (new_len - buf.len); |
| 553 | } |
| 554 | return false; |
| 555 | }; |
| 556 | |
| 557 | cur_end_index = node.trySetEndIndex(cur_end_index, new_end_index) orelse { |
| 558 | return true; |
| 559 | }; |
| 560 | } |
| 561 | } |
| 562 | |
| 563 | fn remap( |
| 564 | context: *anyopaque, |
| 565 | memory: []u8, |
| 566 | alignment: Alignment, |
| 567 | new_len: usize, |
| 568 | return_address: usize, |
| 569 | ) ?[*]u8 { |
| 570 | return if (resize(context, memory, alignment, new_len, return_address)) memory.ptr else null; |
| 571 | } |
| 572 | |
| 573 | fn free(ctx: *anyopaque, buf: []u8, alignment: Alignment, ret_addr: usize) void { |
| 574 | const arena: *ArenaAllocator = @ptrCast(@alignCast(ctx)); |
| 575 | _ = alignment; |
| 576 | _ = ret_addr; |
| 577 | |
| 578 | assert(buf.len > 0); |
| 579 | |
| 580 | const node = arena.loadFirstNode().?; |
| 581 | const cur_buf_ptr: [*]u8 = @as([*]u8, @ptrCast(node)) + @sizeOf(Node); |
| 582 | |
| 583 | var cur_end_index = node.loadEndIndex(); |
| 584 | while (true) { |
| 585 | if (cur_buf_ptr + cur_end_index != buf.ptr + buf.len) { |
| 586 | // Not the most recent allocation; we cannot free it. |
| 587 | return; |
| 588 | } |
| 589 | const new_end_index = cur_end_index - buf.len; |
| 590 | cur_end_index = node.trySetEndIndex(cur_end_index, new_end_index) orelse { |
| 591 | return; |
| 592 | }; |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | const std = @import("std"); |
| 597 | const assert = std.debug.assert; |
| 598 | const mem = std.mem; |
| 599 | const Allocator = std.mem.Allocator; |
| 600 | const Alignment = std.mem.Alignment; |
| 601 | |
| 602 | test "reset with preheating" { |
| 603 | var arena_allocator = ArenaAllocator.init(std.testing.allocator); |
| 604 | defer arena_allocator.deinit(); |
| 605 | // provides some variance in the allocated data |
| 606 | var rng_src = std.Random.DefaultPrng.init(std.testing.random_seed); |
| 607 | const random = rng_src.random(); |
| 608 | var rounds: usize = 25; |
| 609 | while (rounds > 0) { |
| 610 | rounds -= 1; |
| 611 | _ = arena_allocator.reset(.retain_capacity); |
| 612 | var alloced_bytes: usize = 0; |
| 613 | const total_size: usize = random.intRangeAtMost(usize, 256, 16384); |
| 614 | while (alloced_bytes < total_size) { |
| 615 | const size = random.intRangeAtMost(usize, 16, 256); |
| 616 | const alignment: Alignment = .@"32"; |
| 617 | const slice = try arena_allocator.allocator().alignedAlloc(u8, alignment, size); |
| 618 | try std.testing.expect(alignment.check(@intFromPtr(slice.ptr))); |
| 619 | try std.testing.expectEqual(size, slice.len); |
| 620 | alloced_bytes += slice.len; |
| 621 | } |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | test "reset while retaining a buffer" { |
| 626 | var arena_allocator = ArenaAllocator.init(std.testing.allocator); |
| 627 | defer arena_allocator.deinit(); |
| 628 | const a = arena_allocator.allocator(); |
| 629 | |
| 630 | // Create two internal buffers |
| 631 | _ = try a.alloc(u8, 1); |
| 632 | _ = try a.alloc(u8, 1000); |
| 633 | |
| 634 | try std.testing.expect(arena_allocator.state.used_list != null); |
| 635 | |
| 636 | // Check that we have at least two buffers |
| 637 | try std.testing.expect(arena_allocator.state.used_list.?.next != null); |
| 638 | |
| 639 | // This retains the first allocated buffer |
| 640 | try std.testing.expect(arena_allocator.reset(.{ .retain_with_limit = 1 })); |
| 641 | try std.testing.expect(arena_allocator.state.used_list.?.next == null); |
| 642 | } |