stm

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 29, 2022 License: MIT Imports: 2 Imported by: 1

Documentation

Overview

Package stm provides utility types and functions for setting up state machines in Go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RunMachine

func RunMachine[Machine StateMachine[Machine]](machine Machine, startState StateID) error

Utility function for running a state machine. Keeps running every configured state function (starting with the given startState), and transitions to new states as they return. Keeps running until an error occurs. The type parameter constraint ensures that the machine configures states for itself.

func SetTimer

func SetTimer(duration time.Duration, event Event)

Utility function for setting a timer and triggering the given state machine event on expiry. Typically run in a goroutine, to later listen on the event.

Types

type Event

type Event chan Trigger

An event is something that can happen when a state machine receives a trigger. Implemented as a channel, to allow for concurrent communication with the state machine, and listening for the event.

type StateFunc

type StateFunc[Machine any] func(Machine) (nextState StateID, err error)

A function to run when in a given state. Returns when transitioning states (typically after an event triggers), or when an error occurs. Takes a type parameter for the type of state machine to execute on.

type StateID

type StateID int

Uniquely identifies a state in a state machine. Typically used with iota for easy enumeration.

type StateMachine

type StateMachine[Machine any] interface {
	// Returns the configured states for this state machine.
	States() States[Machine]

	// Manages the machine's states, and executes its state functions until an error occurs.
	// Typically calls the RunMachine function provided by this package.
	Run() error
}

A state machine is a type with a configured set of states and corresponding state functions, and a method for running the machine. The type parameter here is to avoid self-reference, but typically points back to the implementer.

type States

type States[Machine any] map[StateID]StateFunc[Machine]

A map of possible states for a state machine. Takes a type parameter for the type of state machine to attach to.

type Trigger

type Trigger struct{}

A signal that may trigger a change in a state machine, typically caused by outside input. Implemented as an empty struct in order to take 0 space.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL