Kinda a basic question but a little context:
I’m parsing a UDP packet as a struct called Packet
that copies and allocates the bytes into buf
like:
const Self = @This();
buf: []const u8 = undefined,
header: *Header = undefined,
pub fn initBuffer(allocator: Allocator, src: []const u8) !Self {
const buf = try allocator.alloc(u8, src.len);
errdefer allocator.free(buf);
@memcpy(buf[0..], src);
const packet: Self = .{
.buf = buf,
.header = @ptrCast(@alignCast(buf[0..min_packet_size])),
};}
See full source: Github: Packet.zig
The header (first 36 bytes) goes into an internal packed struct
called Header
.
I have some methods on the struct to read/parse the header values.
I understand for primitive values I can use self
:
/// Packet byte length (header + payload)
pub fn size(self: Self) u16 {
return self.header.size;
}
and the compiler optimises whether or not self
is copied, I don’t need to care, right?
My question is do I need to care when returning a pointer? For example:
/// Device MAC address
pub fn target(self: Self) *const [6]u8 {
return std.mem.asBytes(&self.header.target)[0..6];
}
Do I use self: Self
or self: *Self
?
I think the first is correct because I’m not mutating self
and self.header
is already a pointer to allocated memory. I’m not returning a stack pointer, right?
Thanks!