Files
bun.sh/src/shell/RefCountedStr.zig
taylor.fish 437e15bae5 Replace catch bun.outOfMemory() with safer alternatives (#22141)
Replace `catch bun.outOfMemory()`, which can accidentally catch
non-OOM-related errors, with either `bun.handleOom` or a manual `catch
|err| switch (err)`.

(For internal tracking: fixes STAB-1070)

---------

Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
2025-08-26 12:50:25 -07:00

48 lines
1.0 KiB
Zig

const RefCountedStr = @This();
refcount: u32 = 1,
len: u32 = 0,
ptr: [*]const u8 = undefined,
const debug = bun.Output.scoped(.RefCountedEnvStr, .hidden);
pub fn init(slice: []const u8) *RefCountedStr {
debug("init: {s}", .{slice});
const this = bun.handleOom(bun.default_allocator.create(RefCountedStr));
this.* = .{
.refcount = 1,
.len = @intCast(slice.len),
.ptr = slice.ptr,
};
return this;
}
pub fn byteSlice(this: *RefCountedStr) []const u8 {
if (this.len == 0) return "";
return this.ptr[0..this.len];
}
pub fn ref(this: *RefCountedStr) void {
this.refcount += 1;
}
pub fn deref(this: *RefCountedStr) void {
this.refcount -= 1;
if (this.refcount == 0) {
this.deinit();
}
}
fn deinit(this: *RefCountedStr) void {
debug("deinit: {s}", .{this.byteSlice()});
this.freeStr();
bun.default_allocator.destroy(this);
}
fn freeStr(this: *RefCountedStr) void {
if (this.len == 0) return;
bun.default_allocator.free(this.ptr[0..this.len]);
}
const bun = @import("bun");