`@Struct`s with both fields and functions

I’m making a server, and I have a lot of packet definitions. In order to simplify these, I want to be able to define them with a comptime function that can take inputs like these:

pub const intention = Packet(&.{
    .{ .name = "proto_version", .real_type = i32, .repr_type = varint },
    .{ .name = "server_address", .real_type = []const u8, .repr_type = string },
    .{ .name = "server_port", .real_type = u16, .repr_type = integer(u16) },
    .{ .name = "intent", .real_type = i32, .repr_type = varint },
});

And return a struct similar to this:

pub const intention = struct {
    proto_version: i32,
    server_address: []const u8,
    server_port: u16,
    intent: i32,

    pub fn serialize(self: intention, ser: *Serializer) !void {
        try varint.serialize(self.proto_version, ser);
        try string.serialize(self.server_address, ser);
        try integer(u16).serialize(self.server_port, ser);
        try varint.serialize(self.intent, ser);
    }

    pub fn deserialize(de: *Deserializer) !intention {
        return .{
            .proto_version = try varint.deserialize(de),
            .server_address = try string.deserialize(de),
            .server_port = try integer(u16).deserialize(de),
            .intent = try varint.deserialize(de),
        };
    }
};

I was able to mostly implement this with @Struct, but I ran into the issue of not being able to add functions to the struct. Reading another post, it appears that this is intentional. Is there any other way to do this? I’d probably be fine with dealing with a little bit more complexity of the side of defining things, but I would like to the keep the API of the packets themselves the same.

Depending on how complex your requirements are, you could write a function that takes your @Struct type as an argument and returns a type with the methods you’re interested in having.

How would I be able to merge the functions and the fields into one type? I want to be able to use method syntax (such as intention.serialize(packet, serializer)), and struct initialization syntax:

var packet: intention = .{
    .proto_version = 778,
    .server_address = "127.0.0.1",
    .server_port = 25535,
    .intent = 1,
};

You can do

pub const PacketSpec = struct {
    name: []const u8,
    real_type: type,
    repr_type: ???,
};
pub fn Packet(specs: []const PacketSpect) type {
   // logic for creating a Packet
}
pub fn Intention(T: type) type {
  return struct {
    const ResultIntention = @This();

    packet: T,

    pub fn serialize(self: ResultIntention, serializer: *Serializer) !void {
      // implement serializing
    }

    pub fn deserialize(deserializer: *Deserializer) !ResultIntention {
        // implement deserializing
    }
  };
}

then you can do

pub const ServerIntention = Intention(Packet(&.{
  // your spec
}));

Intention is one of the packets, and I don’t want the data of the packet to be nested in a deeper type. I want the layout of the type to have both the data and the serialize/deserialize functions in the same struct.

It might be easier to just run some code in the build.zig to generate the packets from a JSON file.

still, the idea is the same, you basically accept that you have to create a wrapper type, or you define the rules for serializing/deserializing out of band. You can do it in build.zig but that requires doing the code generation logic yourself which can be more complicated than needed.

To expand on the previous answer:

pub const PacketField = struct {
    name: []const u8,
    real_type: type,
    repr_type: ReprType,
};

pub fn Packet(comptime fields: []const PacketSpect) type {
    return @Struct(.{});
}

// Decouple implementation from the data
pub fn serializer(ptr: anytype) PacketSerializer(@TypeOf(ptr)) {
    return .{ .ptr = ptr };
}

fn PacketSerializer(comptime Ptr: type)  type {
    return struct {
        ptr: Ptr,

        const P = @TypeInfo(Ptr).pointer.child;

        pub fn serialize(self: @This(), writer: *std.Io.Writer) !void {
            try writer.writeStruct(self.ptr.*, .little);
        }

        pub fn deserialize(self: @This(), reader: *std.Io.Reader) !void {
            self.ptr.* = try reader.takeStruct(P, .little);
        }
    };
}

// ...

pub const Intention = Packet(intention_fields);

pub fn processIntentions(socket: *std.Io.Writer, intentions: []const Intention) !void {
    for (intentions) |*intention| intention.version = PROTO_VERSION;
    for (intentions) |*intention| serializer(intention).serialize(socket);
}

Regarding system design advice - I too used to be like “I want to have a method”, and then fight the compiler and the universe. That is a valid approach, but it has trade-offs. That will reflect onto your library. In real projects. You can try to make a wrapper type that builds on this foundation, but you can hardly detach a tightly coupled implementation to a data type. Zig is very deliberate and well designed in what and how it allows you to do things. Even this wrapper thing is one of multiple approaches (e.g. free functions, …), and honestly you might find that creating a custom reader/writer interface for your library and not supplying a serialization method might prove as a better call (might eliminate the need to have one in the first place. Another, in my opinion more elegant is to have the @Struct embedded inside the non-dump type, and accept that in order to get the fields one would go through intermediary field access:

pub const PacketField = struct {
    name: []const u8,
    real_type: type,
    repr_type: ReprType,
};

pub fn Packet(comptime fields: []const PacketSpect) type {
    return struct {
        data: Data,

        const Data = @Struct(.{});

        pub fn serialize(self: *const @This(), writer: *std.Io.Writer) !void {
            try writer.writeStruct(self.data, .little);
        }

        pub fn deserialize(self: *@This(), reader: *std.Io.Reader) !void {
            self.data = try reader.takeStruct(Data, .little);
        }
    };
}

// ...

pub const Intention = Packet(intention_fields);

pub fn processIntentions(socket: *std.Io.Writer, intentions: []Intention) !void {
    for (intentions) |*intention| intention.data.version = PROTO_VERSION;
    for (intentions) |*intention|intention.serialize(socket);
}

In the end what you should focus on is that your library is maintainable, flexible, performant and safe, not spend days to get it to having a “cool way” to do a thing just because you stubbornly refuse to relax your syntactic requirements (e.g.I WILL NEVER ACCEPT HAVING TO TYPE intention.data.version INSTEAD OF intention.version, IF I CAN’T ALSO TYPE intention.serialize() instead of socket.writeStruct(intention)!!!). These types of requirements are added complexity into a system that should pour all its complexity into solving the actual core of the problems, e.g. how you organize and transform the data. Having a “single struct serialize” function reeks of object oriented design and will likely make you write code that will operate on single intention instead of what is the more common case, e.g. I have a bunch of these things and I should serialize a bunch of them at once to help the CPU and memory work most efficiently. Coming from a guy who spend years trying to do things like that, and years before that C++ template metaprogramming pointless overengineered bs that could have just been free functions, or generated in some other manner; which I will never get back, and in the end made the experience worse.


Edit:

Fixed code in first example.

This seems more like a job for codegen in the build system using addWriteFiles or some custom tooling that it can call to generate it based on a structured API specification.