bt_bencode icon indicating copy to clipboard operation
bt_bencode copied to clipboard

Add serializer for Option and enumerable types

Open angrynode opened this issue 2 months ago • 2 comments

I've been working around the serializer implementations by using skip_serializing_if attributes on struct fields to avoid serializing an empty option, vec or map (for example here)

I'm wondering if this should be the default and if you'd accept a PR for this in this library ? :)

angrynode avatar Nov 06 '25 17:11 angrynode

I understand the frustration about serializing "empty" fields; I have run into the same issue when using other Serde based libraries. However, I am hesitant to make changes to the default.

First, is there a way to request serialization if the field is an empty value? I believe you can only skip serialization via field attributes but you cannot request serialization if the value is empty.

Second, serde_json and other Serde based libraries already require the skip_serializing_if field attribute for the same use case. Specifically for bencode, for Option, it might be valid to serialize nothing because there is no None equivalent in bencode. However, for maps and sequences like Vec, it is still valid to encode an empty dictionary or empty list.

bluk avatar Nov 07 '25 00:11 bluk

That's a very good point, i didn't realize there were empty dicts/lists, but you are correct it's just de/le in bencode. So probably it's better to stick with skip_serializing_if in those cases. However, it would be possible to do that by checking len in serialize_map (etc).

As for options, i'm not really familiar with serde internals but it seems that simply returning from serialize_none works fine. Only deserialization of Option<S> is not happy when S is a struct, because it doesn't find the inner fields. I'm not sure what to do about this.

angrynode avatar Nov 13 '25 17:11 angrynode