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

Fix indexer value conversion #792

Merged
merged 1 commit into from
Oct 24, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 18 additions & 0 deletions Jint.Tests/Runtime/Domain/IntegerIndexer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
namespace Jint.Tests.Runtime.Domain
{
public class IntegerIndexer
{
private readonly int[] data;

public IntegerIndexer()
{
data = new[] {123, 0, 0, 0, 0};
}

public int this[int i]
{
get => data[i];
set => data[i] = value;
}
}
}
16 changes: 16 additions & 0 deletions Jint.Tests/Runtime/InteropTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2249,5 +2249,21 @@ public void ShouldOverrideMembers()

Assert.Equal("Orange", engine.Execute("m.Member1").GetCompletionValue().ToString());
}

[Fact]
public void SettingValueViaIntegerIndexer()
{
var engine = new Engine(cfg => cfg.AllowClr(typeof(FloatIndexer).GetTypeInfo().Assembly));
engine.SetValue("log", new Action<object>(Console.WriteLine));
engine.Execute(@"
var domain = importNamespace('Jint.Tests.Runtime.Domain');
var fia = new domain.IntegerIndexer();
log(fia[0]);
");

Assert.Equal(123, engine.Execute("fia[0]").GetCompletionValue().AsNumber());
engine.Execute("fia[0] = 678;");
Assert.Equal(678, engine.Execute("fia[0]").GetCompletionValue().AsNumber());
}
}
}
10 changes: 9 additions & 1 deletion Jint/Runtime/Descriptors/Specialized/IndexDescriptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,15 @@ protected internal override JsValue CustomValue
ExceptionHelper.ThrowInvalidOperationException("Indexer has no public setter.");
}

object[] parameters = { _key, value?.ToObject() };
var obj = value?.ToObject();

// attempt to convert to expected type
if (obj != null && obj.GetType() != _indexer.PropertyType)
{
obj = _engine.ClrTypeConverter.Convert(obj, _indexer.PropertyType, CultureInfo.InvariantCulture);
}

object[] parameters = { _key, obj };
try
{
setter!.Invoke(_target, parameters);
Expand Down