diff --git a/src/neo/VM/Helper.cs b/src/neo/VM/Helper.cs index 7e73eff3be..f1999fe47d 100644 --- a/src/neo/VM/Helper.cs +++ b/src/neo/VM/Helper.cs @@ -15,6 +15,30 @@ namespace Neo.VM { public static class Helper { + public static ScriptBuilder CreateArray(this ScriptBuilder sb, IReadOnlyList list = null) + { + if (list is null || list.Count == 0) + return sb.Emit(OpCode.NEWARRAY0); + for (int i = list.Count - 1; i >= 0; i--) + sb.EmitPush(list[i]); + sb.EmitPush(list.Count); + return sb.Emit(OpCode.PACK); + } + + public static ScriptBuilder CreateMap(this ScriptBuilder sb, IReadOnlyDictionary map = null) + { + sb.Emit(OpCode.NEWMAP); + if (map != null) + foreach (var p in map) + { + sb.Emit(OpCode.DUP); + sb.EmitPush(p.Key); + sb.EmitPush(p.Value); + sb.Emit(OpCode.SETITEM); + } + return sb; + } + public static ScriptBuilder Emit(this ScriptBuilder sb, params OpCode[] ops) { foreach (OpCode op in ops) diff --git a/tests/neo.UnitTests/VM/UT_Helper.cs b/tests/neo.UnitTests/VM/UT_Helper.cs index 03274d6195..77f07a7821 100644 --- a/tests/neo.UnitTests/VM/UT_Helper.cs +++ b/tests/neo.UnitTests/VM/UT_Helper.cs @@ -68,6 +68,48 @@ public void TestEmitAppCall1() CollectionAssert.AreEqual(tempArray, sb.ToArray()); } + [TestMethod] + public void TestEmitArray() + { + var expected = new BigInteger[] { 1, 2, 3 }; + var sb = new ScriptBuilder(); + sb.CreateArray(expected); + + using var engine = ApplicationEngine.Create(TriggerType.Application, null, null); + engine.LoadScript(sb.ToArray()); + Assert.AreEqual(VMState.HALT, engine.Execute()); + + CollectionAssert.AreEqual(expected, engine.ResultStack.Pop().Select(u => u.GetInteger()).ToArray()); + + expected = new BigInteger[] { }; + sb = new ScriptBuilder(); + sb.CreateArray(expected); + + using var engine2 = ApplicationEngine.Create(TriggerType.Application, null, null); + engine2.LoadScript(sb.ToArray()); + Assert.AreEqual(VMState.HALT, engine2.Execute()); + + Assert.AreEqual(0, engine2.ResultStack.Pop().Count); + } + + [TestMethod] + public void TestEmitMap() + { + var expected = new Dictionary() { { 1, 2 }, { 3, 4 } }; + var sb = new ScriptBuilder(); + sb.CreateMap(expected); + + using var engine = ApplicationEngine.Create(TriggerType.Application, null, null); + engine.LoadScript(sb.ToArray()); + Assert.AreEqual(VMState.HALT, engine.Execute()); + + var map = engine.ResultStack.Pop(); + var dic = map.ToDictionary(u => u.Key, u => u.Value); + + CollectionAssert.AreEqual(expected.Keys, dic.Keys.Select(u => u.GetInteger()).ToArray()); + CollectionAssert.AreEqual(expected.Values, dic.Values.Select(u => u.GetInteger()).ToArray()); + } + [TestMethod] public void TestEmitAppCall2() {