Skip to content

Non-sequential encoding #2668

@Chuckame

Description

@Chuckame

What is your use-case and why do you need this feature?
Currently, a decoder is able of retrieving the element index to decode, that is really powerful when we want to decode encoded data in a different order than the current element order.

Now, if we need to encode the elements in a different order than the descriptor's one, then we have to make complex implementation to buffer the encoded data, by buffering the encoded data and then really encoding it using endStructure.

For sure it works, but it feels like kotlinx-serialization is missing a part of the sequentiality feature, where we are able to select if we want sequential decoding or not, but not for the encoding part.

Describe the solution you'd like
By looking at the generated code made by the serialization plugin, it seems quite "simple" to implement non-sequential encoding as exactly the same way as decoding : a method encodeSequentially that returns true by default for backward compatibility.

When this method returns false, a method getElementIndexToEncode is called unless it returns -1 (encoding done). For each matching index, it encodes the corresponding element's value.

Side note: I've seen some issues about a way to reorder fields, rejected because this job is "do-able" with the current status of the library. But why decodeSequentially and decodeElementIndex exists as it is also still possible to implement in sequential-only way?

For sure I know it's also a feature request for the serialization plugin, which I'll do it.

To finish, having this feature would simplify all the encoders that needs to reorder fields or skip fields, without implementing complex buffering or transformers. It would also make native the AbstractEncoder.encodeElement(descriptor, index): Boolean natively handled as the non-encoded element index wouldn't be returned at all (also a little more performant I suppose). For the last drop-the-mic argument, it will make the sequential mode "parallel" as it will be available in encoding and decoding 🚀

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions