Skip to content
This repository has been archived by the owner on Nov 22, 2023. It is now read-only.

Add factory to GetState #515

Merged
merged 4 commits into from
Nov 6, 2023
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
5 changes: 3 additions & 2 deletions src/Neo.VM/ExecutionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,12 +146,13 @@ public ExecutionContext Clone(int initialPosition)
/// Gets custom data of the specified type. If the data does not exist, create a new one.
/// </summary>
/// <typeparam name="T">The type of data to be obtained.</typeparam>
/// <param name="factory">A delegate used to create the entry. If factory is null, new() will be used.</param>
/// <returns>The custom data of the specified type.</returns>
public T GetState<T>() where T : class, new()
public T GetState<T>(Func<T>? factory = null) where T : class, new()
{
if (!shared_states.States.TryGetValue(typeof(T), out object? value))
{
value = new T();
value = factory is null ? new T() : factory();
shared_states.States[typeof(T)] = value;
}
return (T)value;
Expand Down
17 changes: 17 additions & 0 deletions tests/Neo.VM.Tests/UtExecutionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,28 @@ namespace Neo.Test
[TestClass]
public class UtExecutionContext
{
class TestState
{
public bool Flag = false;
}

[TestMethod]
public void StateTest()
{
var context = new ExecutionContext(Array.Empty<byte>(), -1, new ReferenceCounter());

// Test factory

var flag = context.GetState(() => new TestState() { Flag = true });
Assert.IsTrue(flag.Flag);

flag.Flag = false;

flag = context.GetState(() => new TestState() { Flag = true });
Assert.IsFalse(flag.Flag);

// Test new

var stack = context.GetState<Stack<int>>();
Assert.AreEqual(0, stack.Count);
stack.Push(100);
Expand Down