Can I serialize a struct without any external libraries?

Sometimes we can't expect every single struct from external libraries to derive Serialization and Deserialization traits. Is there any kind of unsafe way to directly convert a struct into some bytes and then also get the struct back from the bytes?

There's no general way to turn a struct into some bytes unless the library provides some way to do so.

You can transmute types into byte arrays, but this is frighteningly fraught with danger — at a minimum, because it won't capture any indirect (e.g. Boxed) state managed by the object. Beyond that, even if the struct is "plain old data" and doesn't have any padding, you have to handle the fact that the struct layout probably isn't guaranteed stable by the library.

If a type exposes enough detail that you can convert it into and from a collection of serializable parts, you can do that to implement de/serialization (e.g. via serde_as). If it doesn't, you're unfortunately just out of luck. You'll need to ask upstream to expose enough information and/or make a fork which implements the de/ser traits.

I mean if I know the types of all the data will be correct and will never emit any problems, how can I just simply serialize and deserialize them without implementing any traits? I've tried transmute but it seems that the it's not possible to transmute between dependently sized types (e.g. vec).

Vec is exactly the kind of type that you can't just turn into a bunch of bytes. The Vec type itself is statically sized (it's a pointer-length-capacity triple), but since it contains indirection, you'd have to traverse the buffer pointer in order to make any sense of its actual contents. Needless to say, you simply shouldn't do that, if you don't even understand its memory layout.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.