Serde extended serialize_struct()

I'm implementing Serialize for my struct, which required custom data appended after serialization (according to spec).
Current impl consumes serializer and I have issue... Any ideas how to fix are welcome =)

struct Message {
    event_message: String
}

impl Serialize for Message {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer {
        let is_hr = serializer.is_human_readable();
        let mut message = serializer.serialize_struct("Message", 1)?;
        message.serialize_field("Message", &self.event_message)?;
        if  is_hr {
            serializer.serialize_str("")?; // empty but irrelevant for the example
        } else {
            serializer.serialize_bytes(b"")?; // same here
        }
        message.end()
    }
}

How do you think the extra data should be represented? It's not an accident Serde doesn't allow you to do this directly. If you serialize a struct, that's one complete entity. You can't just keep serializing after you finished… for example, how would this look like in JSON? You serialize a map for the struct's fields, and then what? If you write something more there, it's going to be invalid JSON – the structure doesn't fit with the syntax.

You have to specify, in terms of the Serde data model, what the extra data should look like. You can add additional fields to the map generated from the struct. You can start a sequence of which the first item is the struct and the second one is the extra data. But you have to fit it into the data type model in some way.

Here is the problem: https://github.com/decentralized-identity/keri/blob/master/kids/kid0001Comment.md#framing-codes

In general - regardless of serialization format (JSON/CBOR/MSGPack) in most cases serialized data will require appending code (from table in link above), count of attachments and attachments themselves as chunk of data (qb64/qb2).
Have no idea how to fit this into the data type model or if it's possible at all... =(

This looks like the description of a serialization format, not that of a data structure. If you need to serialize in a custom format, you should probably implement a serializer (ie. you are currently trying to use the wrong half of the toolset). You won't be able to change how existing serializers output data.

1 Like

Ok, looking into it. Thanks for the direction.

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.