This commit is contained in:
2025-04-28 16:32:16 -04:00
parent 775212013f
commit cbf554e853

View File

@@ -31,11 +31,27 @@ pub const Error = error{
// ZERO COPY STUFF
// &payload could be a void value that is treated as a pointer to a [*]u8
pub const ZeroCopyMessage = packed struct {
pub const Relay = packed struct {
const Relay = packed struct {
dest: @Vector(4, u8),
payload: void,
pub fn getPayload(self: *align(1) Relay) []u8 {
// const vself: *void = @ptrCast(self);
// var parent: *align(1) ZeroCopyMessage = @fieldParentPtr("bytes", vself);
// if (false) {
// parent = @ptrFromInt(@intFromPtr(parent));
// }
const len: *u16 = @ptrFromInt(@intFromPtr(self) - @sizeOf(u16));
// std.debug.print("relay: {*}\n", .{self});
// std.debug.print("inPayload: {*}\n", .{parent});
// std.debug.print("len: {d}\n", .{len.*});
// std.debug.print("len: {d}\n", .{parent.length});
// return @as([*]u8, @ptrCast(&self.payload))[0..3];
// return @as([*]u8, @ptrCast(&self.payload))[0 .. parent.length - @sizeOf(Relay)];
return @as([*]u8, @ptrCast(&self.payload))[0 .. len.* - @sizeOf(Relay)];
}
};
pub const Connection = packed struct {
const Connection = packed struct {
src_port: u16, // random number > 1024
dest_port: u16, // random number > 1024
seq_num: u32 = 0,
@@ -43,6 +59,11 @@ pub const ZeroCopyMessage = packed struct {
reserved: u8 = 0,
options: ConnectionOptions = .{},
payload: void,
pub fn getPayload(self: *align(1) Connection) []u8 {
const len: *u16 = @ptrFromInt(@intFromPtr(self) - @sizeOf(u16));
return @as([*]u8, @ptrCast(&self.payload))[0 .. len.* - @sizeOf(Connection)];
}
};
const Self = @This();
@@ -70,6 +91,9 @@ pub const ZeroCopyMessage = packed struct {
else => Error.UnknownSaprusType,
};
}
pub fn toNativeBytes() void {}
pub fn toNetworkBytes() void {}
};
test "testing variable length zero copy struct" {
@@ -80,9 +104,11 @@ test "testing variable length zero copy struct" {
const zcm: *align(1) ZeroCopyMessage = @ptrCast(bytes.ptr);
zcm.type = .relay;
zcm.length = 3;
std.debug.print("{any}\n", .{zcm});
std.debug.print("{any}\n", .{(try zcm.getSaprusTypePayload()).relay});
zcm.length = 64;
std.debug.print("pre: {*}\n", .{zcm});
// std.debug.print("{any}\n", .{(try zcm.getSaprusTypePayload()).relay});
std.debug.print("{x}\n", .{(try zcm.getSaprusTypePayload()).relay.getPayload()});
std.debug.print("{d}\n", .{(try zcm.getSaprusTypePayload()).relay.getPayload().len});
if (false) {
// Illegal behavior
std.debug.print("{any}\n", .{(try zcm.getSaprusTypePayload()).connection});