#cannot serialize custom struct using std.zon.stringify

1 messages · Page 1 of 1 (latest)

hasty obsidian
#

ive got this code for my matrix struct:

pub fn Matrix(comptime T: type) type {
    return struct {
        const Self = @This();

        rows: usize,
        cols: usize,
        data: []T,
        allocator: std.mem.Allocator,

        pub fn init(allocator: std.mem.Allocator, m: usize, n: usize) !Self {
            return Self{
                .rows = m,
                .cols = n,
                .data = try allocator.alloc(T, n * m),
                .allocator = allocator,
            };
        }
       // other stuff
  };
}

and im trying to use std.zon.stringify to save the matrix into a file (to load it later). but when i try to serialize it:

try stringify.serialize(Mat, options, writer);

I get this compile time error:

/.../zig-0.15.0/lib/std/debug.zig:554:14: error: reached unreachable code
    if (!ok) unreachable; // assertion failure
             ^~~~~~~~~~~
/.../zig-0.15.0/lib/std/zon/stringify.zig:493:28: note: called at comptime here
            comptime assert(canSerializeType(@TypeOf(val)));
                     ~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

idk how my struct is unserializeable, maybe one of the members cause the problem? My guess is the data slice (although it worked fine when i dont use heap allocated memory). Thanks in advance!

zenith finch
#

IIRC the issue is that you can't serialize an allocator.

frank raft
#

yeah it's definitely the allocator

#

you shouldn't really store allocators in collections like this anyway

#

the standard library is deprecating that pattern

zenith finch
#

But if you still need to keep a pattern like this for some reason, you can separate the serializable part into a separate struct.

hasty obsidian
#

ah alright, thanks guys I'll try that out

#

On a separate note what pattern should I use for allocators?

#

I mean, I guess I can still easily have a data as a slice in the serialization struct

frank raft