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
292 stars 62 forks source link

[FEATURE REQUEST] FieldAddress attribute to jump to address read and jump back to previous position #178

Open sn4k3 opened 2 years ago

sn4k3 commented 2 years ago

I often deal with jumps on structures and need to create a new class rather than one and seek in between of serializations, sometimes is usefull to have the field address rather than sequential enforced

My proposal:

[FieldAddress(long offset|nameof(field), SeekOrigin origin = SeekOrigin.Begin, bool returnToCurrentPosition = true)]
[FieldOrder(0)] uint MyField1;
[FieldOrder(1)] uint MyField2;
[FieldOrder(2)] uint MyField3;
example 1: [FieldAddress(40)] uint MyField1;
stream.Position; // eg. 20
(Serialize MyField1) // at stream.Position 40
stream.Position = 20; // Because of returnToCurrentPosition = true
(Serialize MyField2) // at stream.Position 20
(Serialize MyField3) // at stream.Position 24
example 2: [FieldAddress(nameof(MyField2Address), returnToCurrentPosition = false)] uint MyField1;
stream.Position; // eg. 20
(Serialize MyField1) // at stream.Position 40
(Serialize MyField2) // at stream.Position 44
(Serialize MyField3) // at stream.Position 48
// Does not return to old position and continue from here

This will allow complex jumping, dazy chain, and unify classes. Another use case:

class Header:

[FieldAddress(-4, SeekOrigin.End, true)]
[FieldOrder(0)] uint Checksum; // Last uint on the file
[FieldAddress(0, SeekOrigin.Begin, true)] // Make sure we are on position 0
[FieldOrder(1)] uint MyHeader1; // stream.position 0
[FieldOrder(2)] uint MyHeader2; // stream.position 4
[FieldOrder(3)] uint MyHeader3; // stream.position 8
[FieldOrder(4)] uint MyHeader4; // stream.position 12

This way i dont need to deserialize all file first in order to validate my checksum Of course this will raise other problem, on create file from scrath, in this case we have to write header as last operation or SetLength of file before hand