Skip to content

Commit

Permalink
fix: fix nullable arrays (#621)
Browse files Browse the repository at this point in the history
  • Loading branch information
TimothyMakkison authored Aug 4, 2023
1 parent d0eb471 commit 237be62
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,14 @@ or CollectionType.IEnumerable
// a single Array.Clone / cast mapping call should be sufficient and fast,
// use a for loop mapping otherwise.
if (!elementMapping.IsSynthetic)
return new ArrayForMapping(ctx.Source, ctx.Target, elementMapping, elementMapping.TargetType);
{
// upgrade nullability of element type
var targetValue =
ctx.CollectionInfos.Target.CollectionType == CollectionType.Array
? ctx.Types.GetArrayType(elementMapping.TargetType)
: ((INamedTypeSymbol)ctx.Target).ConstructedFrom.Construct(elementMapping.TargetType);
return new ArrayForMapping(ctx.Source, targetValue, elementMapping, elementMapping.TargetType);
}

return ctx.MapperConfiguration.UseDeepCloning
? new ArrayCloneMapping(ctx.Source, ctx.Target)
Expand Down
13 changes: 13 additions & 0 deletions test/Riok.Mapperly.Tests/Mapping/EnumerableTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,19 @@ public void EnumerableToCustomCollectionWithObjectFactory()
);
}

[Fact]
public Task ArrayToReadOnlyCollectionShouldUpgradeNullability()
{
var source = TestSourceBuilder.Mapping(
"A",
"B",
"class A { public int[] Value { get; set;} }",
"class B { public IReadOnlyCollection<string> Value { get; set; } }"
);

return TestHelper.VerifyGenerator(source, TestHelperOptions.DisabledNullable);
}

[Fact]
public Task ShouldUpgradeNullabilityInDisabledNullableContextInSelectClause()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//HintName: Mapper.g.cs
// <auto-generated />
#nullable enable
public partial class Mapper
{
private partial global::B? Map(global::A? source)
{
if (source == null)
return default;
var target = new global::B();
if (source.Value != null)
{
target.Value = MapToIReadOnlyCollection(source.Value);
}

return target;
}

private global::System.Collections.Generic.IReadOnlyCollection<string?> MapToIReadOnlyCollection(int[] source)
{
var target = new string?[source.Length];
for (var i = 0; i < source.Length; i++)
{
target[i] = source[i].ToString();
}

return target;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public partial class Mapper
return target;
}

private global::D[] MapToDArray(global::C[] source)
private global::D?[] MapToDArray(global::C[] source)
{
var target = new global::D?[source.Length];
for (var i = 0; i < source.Length; i++)
Expand All @@ -35,4 +35,4 @@ public partial class Mapper

return target;
}
}
}

0 comments on commit 237be62

Please sign in to comment.