mirror of
https://git.robbyzambito.me/zaprus
synced 2025-12-20 08:14:50 +00:00
Cleanup asBytes and test it
This commit is contained in:
@@ -91,7 +91,7 @@ pub const ZeroCopyMessage = packed struct {
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Self, allocator: Allocator) void {
|
||||
allocator.free(self.toBytes());
|
||||
allocator.free(self.asBytes());
|
||||
}
|
||||
|
||||
fn getRelay(self: *Self) *align(1) Relay {
|
||||
@@ -143,17 +143,25 @@ pub const ZeroCopyMessage = packed struct {
|
||||
self.length = nativeToBig(@TypeOf(self.length), self.length);
|
||||
}
|
||||
|
||||
pub fn fromBytesUnchecked(bytes: []align(@alignOf(Self)) u8) *Self {
|
||||
return @ptrCast(@alignCast(bytes.ptr));
|
||||
pub fn bytesAsValueUnchecked(bytes: []align(@alignOf(Self)) u8) *Self {
|
||||
return std.mem.bytesAsValue(Self, bytes);
|
||||
}
|
||||
|
||||
pub fn fromBytes(bytes: []align(@alignOf(Self)) u8) !*Self {
|
||||
const res: *Self = @ptrCast(@alignCast(bytes.ptr));
|
||||
return if (bytes.len == res.length + @sizeOf(Self)) res else Error.InvalidMessage;
|
||||
pub fn bytesAsValue(bytes: []align(@alignOf(Self)) u8) !*Self {
|
||||
const res = bytesAsValueUnchecked(bytes);
|
||||
return switch (res.type) {
|
||||
.relay, .connection => if (bytes.len == res.length + @sizeOf(Self))
|
||||
res
|
||||
else
|
||||
Error.InvalidMessage,
|
||||
.file_transfer => Error.NotImplementedSaprusType,
|
||||
else => Error.UnknownSaprusType,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn toBytes(self: *Self) []align(@alignOf(Self)) u8 {
|
||||
return @as([*]align(@alignOf(Self)) u8, @ptrCast(self))[0 .. @sizeOf(Self) + self.length];
|
||||
pub fn asBytes(self: *Self) []align(@alignOf(Self)) u8 {
|
||||
const size = @sizeOf(Self) + self.length;
|
||||
return @as([*]align(@alignOf(Self)) u8, @ptrCast(self))[0..size];
|
||||
}
|
||||
};
|
||||
|
||||
@@ -178,14 +186,14 @@ test "testing variable length zero copy struct" {
|
||||
}
|
||||
|
||||
{
|
||||
const bytes = zcm.toBytes();
|
||||
const bytes = zcm.asBytes();
|
||||
|
||||
// Print the message as hex using the network byte order
|
||||
try zcm.networkFromNativeEndian();
|
||||
// We know the error from nativeFromNetworkEndian is unreachable because
|
||||
// it would have returned an error from networkFromNativeEndian.
|
||||
defer zcm.nativeFromNetworkEndian() catch unreachable;
|
||||
std.debug.print("network bytes: {s}\n", .{bytes});
|
||||
std.debug.print("network bytes: {x}\n", .{bytes});
|
||||
std.debug.print("bytes len: {d}\n", .{bytes.len});
|
||||
}
|
||||
|
||||
@@ -193,6 +201,8 @@ test "testing variable length zero copy struct" {
|
||||
// Illegal behavior
|
||||
std.debug.print("{any}\n", .{(try zcm.getSaprusTypePayload()).connection});
|
||||
}
|
||||
|
||||
try std.testing.expectEqualDeep(zcm, try ZeroCopyMessage.bytesAsValue(zcm.asBytes()));
|
||||
}
|
||||
|
||||
/// All Saprus messages
|
||||
|
||||
Reference in New Issue
Block a user