JSON serialize for arrays problem

Here's a simple serialization and deserialization of 2D vector data. There are two ways to represent that.


type LLVec2Data = [f32;2];
pub struct LLVec2 {
        x: f32,
        y: f32
}

The first one serializes nicely, with the JSON representation [1.0, 2.0]. But you can't attach functions to a type, only to a struct. Which is annoying for numeric structs like this, where all the vector operations are needed.

The second one serializes in a bulky way: LLVec2 { x: 1.0, y: 2.0 }

and can have functions attached to the struct.

I have existing data files, gigabytes of them, serialized with the "array format", and want to read them into the LLVec2 type, so I can compute with them. I'd also like to serialize LLVec2 into the "array format" instead of the struct format. How to do that? Is it possible to construct additional serializers and deserializers, and do they have to be as bulky as the examples?

Deserializing [1.0, 2.0] into LLVec2 does work with the implementations created by serde_derive. For serialization, you have two options.

  1. Instead of a type alias, you can define a newtype. serde_json serializes a newtype identical to its inner element. Newtype wrappers fulfil a similar use case to type aliases, but since they create a new type, you can attach functions to them.
#[derive(Serialize,Deserialize, Debug)]
struct LLVec2Data([f32;2]);
  1. You can use a different crate to derive the Serialize implementations. serde_tuple can derive implementations for LLVec2 which convert to/from [1.0, 2.0].

Or you can make it a tuple struct.

pub struct LLVec2(f32, f32);

Ah. That worked. Converted most of the code to serde JSON serialization and deserialization, and got rid of a few hundred lines of code. Also avoided having to write more of that stuff. It's all for debug playback, anyway.

A "newtype" is really a tuple of length 1, and I had to write "self.0" too much, but it all works now.
Thanks.