jefffhaynes / BinarySerializer

A declarative serialization framework for controlling formatting of data at the byte and bit level using field bindings, converters, and code.
MIT License
291 stars 62 forks source link

InvalidOperationException Reverse binding not allowed on FieldValue attributes #202

Open WilbertOnGithub opened 1 year ago

WilbertOnGithub commented 1 year ago

First of all, great library when having to deal with this stuff. However, I think I encountered a little bit of a snag.

I'm trying to use the FieldCrc16 attribute to calculate the CRC. I've noticed that when the CRC field/property is at the end of the message it works fine (see example below).

public class Packet
{
    [FieldOrder(0)]
    [FieldCrc16(nameof(Crc))]       
    public int PacketType { get; set; } 

    [FieldOrder(1)]
    public ushort Crc { get; set; }
}

However, if I swap the fieldorder (I have a requirement where the CRC value needs to be at the beginning of the message) like this:

public class Packet
{
    [FieldOrder(0)]
    public ushort Crc { get; set; }

    [FieldOrder(1)]
    [FieldCrc16(nameof(Crc))]       
    public int PacketType { get; set; }     
}

The serialization fails with the exception InvalidOperationException: Reverse binding not allowed on FieldValue attributes.

What am I missing here?

jefffhaynes commented 1 year ago

Unfortunately you're not missing anything. The nature of serializers is such that they go forward, not backwards. Supporting reverse bindings like this starts to open up all sorts of universe-ending time loops that I just wasn't prepared to tackle (e.g. what if that CRC was part of itself 🤯). This is similar to why things like lookup tables, databases, etc. are also not supported. It's all possible, for some definition of "possible", but at some point it just isn't a serializer anymore.

If that seems like a copout answer, the short answer is because it's really complicated and I probably don't have time to figure it out :). If I'm missing something obvious, please feel free to submit a PR!

WilbertOnGithub commented 1 year ago

Hi Jeff, thanks for the speedy and honest reply - I don't consider it to be a copout answer. I suspected that the backtracking could be problematic. I'm not going to say I will submit a quick PR but I will try to see how we can solve this with our specific issue for this project. Will update this comment with that (upcoming) result.

Might be a good idea to keep this issue alive so that other people who use the library can find this?

Keep up the good work - I've added your library to my list of packages to consider for new projects.