diff options
| author | Feoramund <161657516+Feoramund@users.noreply.github.com> | 2025-06-11 11:36:57 -0400 |
|---|---|---|
| committer | Feoramund <161657516+Feoramund@users.noreply.github.com> | 2025-06-11 11:55:30 -0400 |
| commit | 638a1529a30c4dbcf54b4e65b7f9c8fa034cba1c (patch) | |
| tree | 50ac85a722e5095117508f25aeb3333690c68a8c /core/container/queue/queue.odin | |
| parent | 040d79e1b99d952907167b9688b776920ad1d300 (diff) | |
container/queue: Add `shrink`
Diffstat (limited to 'core/container/queue/queue.odin')
| -rw-r--r-- | core/container/queue/queue.odin | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/core/container/queue/queue.odin b/core/container/queue/queue.odin index 7e3e18075..5c7369a50 100644 --- a/core/container/queue/queue.odin +++ b/core/container/queue/queue.odin @@ -122,6 +122,33 @@ reserve :: proc(q: ^$Q/Queue($T), capacity: int) -> runtime.Allocator_Error { } /* +Shrink a queue's dynamically allocated array. + +This has no effect if the queue was initialized with a backing slice. +*/ +shrink :: proc(q: ^$Q/Queue($T), temp_allocator := context.temp_allocator, loc := #caller_location) { + if q.data.allocator.procedure == runtime.nil_allocator_proc { + return + } + + if q.len > 0 && q.offset > 0 { + // Make the array contiguous again. + buffer := make([]T, q.len, temp_allocator) + defer delete(buffer, temp_allocator) + + right := uint(builtin.len(q.data)) - q.offset + copy(buffer[:], q.data[q.offset:]) + copy(buffer[right:], q.data[:q.offset]) + + copy(q.data[:], buffer[:]) + + q.offset = 0 + } + + builtin.shrink(&q.data, q.len, loc) +} + +/* Get the element at index `i`. This will raise a bounds checking error if `i` is an invalid index. |