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