implements minimal state switching

This commit is contained in:
Ben Bierens 2023-02-08 14:54:29 +01:00 committed by Mark Spanbroek
parent 21c6fc5d09
commit 894cbe4a0b
No known key found for this signature in database
GPG Key ID: FBE3E9548D427C00
2 changed files with 30 additions and 3 deletions

View File

@ -5,6 +5,13 @@ type
AsyncStateMachine* = ref object of RootObj
AsyncState* = ref object of RootObj
method start*(stateMachine: AsyncStateMachine, initialState: AsyncState) =
method run*(state: AsyncState): Future[?AsyncState] {.base.} =
discard
proc runState(state: AsyncState): Future[void] {.async.} =
if next =? await state.run():
await runState(next)
proc start*(stateMachine: AsyncStateMachine, initialState: AsyncState) =
asyncSpawn runState(initialState)

View File

@ -4,16 +4,27 @@ import pkg/chronos
import codex/utils/asyncstatemachine
import ../helpers/eventually
type TestState = ref object of AsyncState
type
TestState = ref object of AsyncState
State1 = ref object of AsyncState
State2 = ref object of AsyncState
var runInvoked = 0
var state2runInvoked = 0
method run(state: TestState): Future[?AsyncState] =
method run(state: TestState): Future[?AsyncState] {.async.} =
inc runInvoked
method run(state: State1): Future[?AsyncState] {.async.} =
return some AsyncState(State2.new())
method run(state: State2): Future[?AsyncState] {.async.} =
inc state2runInvoked
suite "async state machines":
setup:
runInvoked = 0
state2runInvoked = 0
test "creates async state machine":
let sm = AsyncStateMachine.new()
@ -27,3 +38,12 @@ suite "async state machines":
check eventually runInvoked == 1
test "moves to next state when run completes":
let sm = AsyncStateMachine.new()
let state1 = State1.new()
let state2 = State2.new()
sm.start(state1)
check eventually state2runInvoked == 1