Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gracefully handle ctor parameters named by the serialized name #209

Merged
merged 2 commits into from
Dec 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/Nerdbank.MessagePack/Converters/CommonRecords.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ internal record struct PropertyAccessors<TDeclaringType>(
/// <typeparam name="TDeclaringType">The data type whose constructor is to be visited.</typeparam>
/// <param name="Serializers">Serializable properties on the data type.</param>
/// <param name="Deserializers">Deserializable properties on the data type.</param>
internal record MapConstructorVisitorInputs<TDeclaringType>(MapSerializableProperties<TDeclaringType> Serializers, MapDeserializableProperties<TDeclaringType> Deserializers);
/// <param name="ParametersByName">A collection of constructor parameters, with any conflicting names removed.</param>
internal record MapConstructorVisitorInputs<TDeclaringType>(MapSerializableProperties<TDeclaringType> Serializers, MapDeserializableProperties<TDeclaringType> Deserializers, Dictionary<string, IConstructorParameterShape> ParametersByName);

/// <summary>
/// Encapsulates the data passed through <see cref="ITypeShapeVisitor.VisitConstructor{TDeclaringType, TArgumentState}(IConstructorShape{TDeclaringType, TArgumentState}, object?)"/> state arguments
Expand Down
25 changes: 20 additions & 5 deletions src/Nerdbank.MessagePack/StandardVisitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,23 @@ internal StandardVisitor(ConverterCache owner, TypeGenerationContext context)

IConstructorShape? ctorShape = objectShape.Constructor;

Dictionary<string, IConstructorParameterShape>? ctorParametersByName =
ctorShape?.Parameters.ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase);
Dictionary<string, IConstructorParameterShape>? ctorParametersByName = null;
if (ctorShape is not null)
{
ctorParametersByName = new(StringComparer.Ordinal);
foreach (IConstructorParameterShape ctorParameter in ctorShape.Parameters)
{
// Keep the one with the Kind that we prefer.
if (ctorParameter.Kind == ConstructorParameterKind.ConstructorParameter)
{
ctorParametersByName[ctorParameter.Name] = ctorParameter;
}
else if (!ctorParametersByName.ContainsKey(ctorParameter.Name))
{
ctorParametersByName.Add(ctorParameter.Name, ctorParameter);
}
}
}

List<SerializableProperty<T>>? serializable = null;
List<DeserializableProperty<T>>? deserializable = null;
Expand Down Expand Up @@ -147,9 +162,9 @@ internal StandardVisitor(ConverterCache owner, TypeGenerationContext context)

MapSerializableProperties<T> serializableMap = new(serializable?.ToArray());
MapDeserializableProperties<T> deserializableMap = new(propertyReaders);
MapConstructorVisitorInputs<T> inputs = new(serializableMap, deserializableMap);
if (ctorShape is not null)
{
MapConstructorVisitorInputs<T> inputs = new(serializableMap, deserializableMap, ctorParametersByName!);
converter = (MessagePackConverter<T>)ctorShape.Accept(this, inputs)!;
}
else
Expand Down Expand Up @@ -279,7 +294,7 @@ internal StandardVisitor(ConverterCache owner, TypeGenerationContext context)

List<SerializableProperty<TDeclaringType>> propertySerializers = inputs.Serializers.Properties.Span.ToList();

SpanDictionary<byte, DeserializableProperty<TArgumentState>> parameters = constructorShape.Parameters
SpanDictionary<byte, DeserializableProperty<TArgumentState>> parameters = inputs.ParametersByName.Values
.SelectMany<IConstructorParameterShape, (string Name, DeserializableProperty<TArgumentState> Deserialize)>(p =>
{
var prop = (DeserializableProperty<TArgumentState>)p.Accept(this)!;
Expand Down Expand Up @@ -316,7 +331,7 @@ internal StandardVisitor(ConverterCache owner, TypeGenerationContext context)
return new ObjectArrayConverter<TDeclaringType>(inputs.GetJustAccessors(), constructorShape.GetDefaultConstructor(), !this.owner.SerializeDefaultValues);
}

Dictionary<string, int> propertyIndexesByName = new(StringComparer.OrdinalIgnoreCase);
Dictionary<string, int> propertyIndexesByName = new(StringComparer.Ordinal);
for (int i = 0; i < inputs.Properties.Count; i++)
{
if (inputs.Properties[i] is { } property)
Expand Down
30 changes: 30 additions & 0 deletions test/Nerdbank.MessagePack.Tests/MessagePackSerializerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,26 @@
Assert.Equal(value, deserialized);
}

[Fact]
public void CtorParameterNameMatchesSerializedInsteadOfDeclaredName_Roundtrips()
{
this.AssertRoundtrip(new TypeWithConstructorParameterMatchingSerializedPropertyName(2));
}

[Fact]
public void CtorParameterNameMatchesSerializedInsteadOfDeclaredName_DefaultValueWorks()
{
Sequence<byte> seq = new();
MessagePackWriter writer = new(seq);
writer.WriteMapHeader(0);
writer.Flush();

TypeWithConstructorParameterMatchingSerializedPropertyName? deserialized =
this.Serializer.Deserialize<TypeWithConstructorParameterMatchingSerializedPropertyName>(seq, TestContext.Current.CancellationToken);
Assert.NotNull(deserialized);
Assert.Equal(8, deserialized.Marshaled);
}

/// <summary>
/// Carefully writes a msgpack-encoded array of bytes.
/// </summary>
Expand Down Expand Up @@ -496,6 +516,16 @@
public int Sum => this.A + this.B;
}

[GenerateShape]
internal partial record TypeWithConstructorParameterMatchingSerializedPropertyName

Check warning on line 520 in test/Nerdbank.MessagePack.Tests/MessagePackSerializerTests.cs

View check run for this annotation

Codecov / codecov/patch

test/Nerdbank.MessagePack.Tests/MessagePackSerializerTests.cs#L520

Added line #L520 was not covered by tests
{
public TypeWithConstructorParameterMatchingSerializedPropertyName(int otherName = 8)
=> this.Marshaled = otherName;

[PropertyShape(Name = "otherName")]
public int Marshaled { get; set; }
}

[GenerateShape<UnannotatedPoco>]
[GenerateShape<object>]
[GenerateShape<string>]
Expand Down