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

Commit

Permalink
Add factory to GetState (#515)
Browse files Browse the repository at this point in the history
* Add factory to GetState

* Update src/Neo.VM/ExecutionContext.cs

* ut

* Improve ut
  • Loading branch information
shargon committed Nov 6, 2023
1 parent 859417a commit 426e54d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/Neo.VM/ExecutionContext.cs
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
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

0 comments on commit 426e54d

Please sign in to comment.