mem: typed allocation helpers + drop bare malloc/free (Phase 2.2); resolve 0119 as |>-contract clarification
This commit is contained in:
61
examples/0838-memory-helpers.sx
Normal file
61
examples/0838-memory-helpers.sx
Normal file
@@ -0,0 +1,61 @@
|
||||
// Typed allocation helpers over the Allocator protocol (std/mem.sx):
|
||||
// create/destroy (one T), alloc/free (slices), clone, resize, and the
|
||||
// bytes-level mem_realloc. Free functions — direct calls and the
|
||||
// fluent pipe spelling (`context.allocator |> create(Session)`) hit
|
||||
// the same generic machinery. Contents are UNINITIALISED by design
|
||||
// (Zig-aligned): assign before reading. TrackingAllocator balances to
|
||||
// zero across every pair.
|
||||
|
||||
#import "modules/std.sx";
|
||||
#import "modules/std/mem.sx";
|
||||
|
||||
Session :: struct { id: s64; score: s64; }
|
||||
|
||||
main :: () {
|
||||
gpa := GPA.init();
|
||||
tracker := TrackingAllocator.init(xx gpa);
|
||||
a : Allocator = xx tracker;
|
||||
|
||||
// create / destroy — direct spelling
|
||||
s := create(a, Session);
|
||||
s.id = 7; s.score = 42;
|
||||
print("create: {} {}\n", s.id, s.score);
|
||||
destroy(a, s);
|
||||
|
||||
// create — fluent pipe spelling
|
||||
p := a |> create(Session);
|
||||
p.id = 1;
|
||||
print("pipe-create: {}\n", p.id);
|
||||
a |> destroy(p);
|
||||
|
||||
// alloc / free — typed slice
|
||||
xs := a |> alloc(s64, 4);
|
||||
xs[0] = 10; xs[1] = 20; xs[2] = 30; xs[3] = 40;
|
||||
print("alloc: {} {} len={}\n", xs[0], xs[3], xs.len);
|
||||
|
||||
// clone — independent copy
|
||||
ys := xs |> clone(a);
|
||||
xs[0] = 99;
|
||||
print("clone: {} (orig {})\n", ys[0], xs[0]);
|
||||
a |> free(ys);
|
||||
|
||||
// resize — grow (copies, old backing freed)
|
||||
zs := xs |> resize(a, 6);
|
||||
zs[5] = 60;
|
||||
print("resize: {} {} len={}\n", zs[1], zs[5], zs.len);
|
||||
// resize — shrink
|
||||
ws := zs |> resize(a, 2);
|
||||
print("shrink: {} {} len={}\n", ws[0], ws[1], ws.len);
|
||||
a |> free(ws);
|
||||
|
||||
// mem_realloc — bytes level
|
||||
raw := a.alloc_bytes(8);
|
||||
q : *s64 = xx raw;
|
||||
q.* = 1234;
|
||||
raw2 := mem_realloc(a, raw, 8, 16, 8);
|
||||
q2 : *s64 = xx raw2;
|
||||
print("realloc: {}\n", q2.*);
|
||||
a.dealloc_bytes(raw2);
|
||||
|
||||
tracker.report();
|
||||
}
|
||||
Reference in New Issue
Block a user