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

Calculate field length #201

Closed bqio closed 1 year ago

bqio commented 1 year ago

Hello!

How can I implement this?

[FieldOrder(1)]
public uint NumberOfPointers { get; set; }
[FieldOrder(2)]
[FieldCount(nameof(NumberOfPointers)) + 1]
public List<uint> Pointers { get; set; }
jefffhaynes commented 1 year ago

You would have to use a ValueConverter. I haven't checked this but it should be something like this. See here for another example.

public class PlusOneConverter : IValueConverter
{
    public object Convert(object value, object parameter, BinarySerializationContext context)
    {
        var count = System.Convert.ToUInt32(value);
        return count + 1;
    }

    public object ConvertBack(object value, object parameter, BinarySerializationContext context)
    {
        var count = System.Convert.ToUInt32(value);
        return count - 1;
    }
}

// ...

[FieldOrder(1)]
public uint NumberOfPointers { get; set; }

[FieldOrder(2)]
[FieldCount(nameof(NumberOfPointers)), ConverterType = typeof(PlusOneConverter)]
public List<uint> Pointers { get; set; }
bqio commented 1 year ago

You would have to use a ValueConverter. I haven't checked this but it should be something like this. See here for another example.

public class PlusOneConverter : IValueConverter
{
    public object Convert(object value, object parameter, BinarySerializationContext context)
    {
        var count = System.Convert.ToUInt32(value);
        return count + 1;
    }

    public object ConvertBack(object value, object parameter, BinarySerializationContext context)
    {
        var count = System.Convert.ToUInt32(value);
        return count - 1;
    }
}

// ...

[FieldOrder(1)]
public uint NumberOfPointers { get; set; }

[FieldOrder(2)]
[FieldCount(nameof(NumberOfPointers)), typeof(PlusOneConverter)]
public List<uint> Pointers { get; set; }

But it works only for FieldEndianness. I don't see second argument in FieldCount attribute.

jefffhaynes commented 1 year ago

Sorry, fixed. I was missing ConverterType =

Endianness has it a default parameter b/c the attribute doesn't make sense without it (not meaningful to bind to an "endianness" field).