machine/machine.go

68 lines
1.5 KiB
Go
Raw Normal View History

2024-04-04 17:33:22 +00:00
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package machine
import (
"errors"
)
type State string
type Stater interface {
AddStates(name ...State)
GetState(name string) State
AddTransition(trigger string, source State, dest State)
AddSubscription(transition string, subscription Subscriber) error
AddModel(m Modeler)
2024-04-04 20:06:45 +00:00
Trigger(transition string) error
2024-04-04 17:33:22 +00:00
CurrentState() State
}
type Definition struct {
states []State
triggers map[string]Transitioner
model Modeler
}
func New(initial State) Stater {
return &Definition{ model: NewModel(initial), triggers: make(map[string]Transitioner) }
}
func (d *Definition) AddStates(name ...State) {
d.states = append(d.states, name...)
}
func (d *Definition) AddTransition(trigger string, source State, dest State) {
d.triggers[trigger] = NewTransition(trigger, source, dest)
}
func (d *Definition) GetState(name string) State {
var r State
for _,s := range(d.states) {
if string(s) == name {
return s
}
}
return r
}
func (d *Definition) AddModel(m Modeler) {
d.model = m
}
2024-04-04 20:06:45 +00:00
func (d *Definition) Trigger(transition string) error {
return d.triggers[transition].Run(d.model)
2024-04-04 17:33:22 +00:00
}
func (d *Definition) CurrentState() State {
return d.model.InspectState()
}
func (d *Definition) AddSubscription(transition string, subscription Subscriber) error {
if t,ok := d.triggers[transition]; ok {
t.Subscribe(subscription)
2024-04-04 20:06:45 +00:00
return nil
2024-04-04 17:33:22 +00:00
}
return errors.New("Transition does not exist")
}