Skip to content

Commit 84b368f

Browse files
committed
Fix a bunch of canonicalization issues
1 parent e159959 commit 84b368f

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+1489
-2436
lines changed

src/builtins/utils.zig

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,8 +130,49 @@ pub const TestEnv = struct {
130130

131131
fn rocReallocFn(roc_realloc: *RocRealloc, env: *anyopaque) callconv(.C) void {
132132
_ = env;
133-
_ = roc_realloc;
134-
@panic("Test realloc not implemented yet");
133+
134+
// Basic realloc implementation using the testing allocator
135+
const allocator = std.testing.allocator;
136+
137+
// Calculate where the size metadata is stored for the old allocation
138+
const size_storage_bytes = @max(roc_realloc.alignment, @alignOf(usize));
139+
140+
if (@intFromPtr(roc_realloc.answer) == 0) {
141+
// Initial allocation
142+
const new_total_size = roc_realloc.new_length + size_storage_bytes;
143+
const new_slice = allocator.alloc(u8, new_total_size) catch {
144+
roc_realloc.answer = @ptrFromInt(@as(usize, 0));
145+
return;
146+
};
147+
148+
// Store the total size in metadata
149+
const new_size_ptr: *usize = @ptrFromInt(@intFromPtr(new_slice.ptr) + size_storage_bytes - @sizeOf(usize));
150+
new_size_ptr.* = new_total_size;
151+
152+
// Return pointer to data (after metadata)
153+
roc_realloc.answer = @ptrFromInt(@intFromPtr(new_slice.ptr) + size_storage_bytes);
154+
return;
155+
}
156+
157+
// Reallocation of existing memory
158+
const old_size_ptr: *const usize = @ptrFromInt(@intFromPtr(roc_realloc.answer) - @sizeOf(usize));
159+
const old_total_size = old_size_ptr.*;
160+
const old_base_ptr: [*]u8 = @ptrFromInt(@intFromPtr(roc_realloc.answer) - size_storage_bytes);
161+
162+
const new_total_size = roc_realloc.new_length + size_storage_bytes;
163+
164+
const old_slice = @as([*]u8, @ptrCast(old_base_ptr))[0..old_total_size];
165+
const new_slice = allocator.realloc(old_slice, new_total_size) catch {
166+
roc_realloc.answer = @ptrFromInt(0);
167+
return;
168+
};
169+
170+
// Store the new total size in metadata
171+
const new_size_ptr: *usize = @ptrFromInt(@intFromPtr(new_slice.ptr) + size_storage_bytes - @sizeOf(usize));
172+
new_size_ptr.* = new_total_size;
173+
174+
// Return pointer to data (after metadata)
175+
roc_realloc.answer = @ptrFromInt(@intFromPtr(new_slice.ptr) + size_storage_bytes);
135176
}
136177

137178
fn rocDbgFn(roc_dbg: *const RocDbg, env: *anyopaque) callconv(.C) void {

0 commit comments

Comments
 (0)