From 88ef244a3eb263af0c269656577f86f60d6c0f23 Mon Sep 17 00:00:00 2001 From: pancsta <155631569+pancsta@users.noreply.github.com> Date: Thu, 22 Feb 2024 15:18:28 +0100 Subject: [PATCH] feat: add support for state groups for the Remove relation (#17) --- pkg/machine/machine.go | 11 ++++++++++- pkg/machine/misc.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/pkg/machine/machine.go b/pkg/machine/machine.go index f34c082..fd23096 100644 --- a/pkg/machine/machine.go +++ b/pkg/machine/machine.go @@ -86,10 +86,19 @@ type Machine struct { // New creates a new Machine instance, bound to context and modified with // optional Opts func New(ctx context.Context, states States, opts *Opts) *Machine { + // parse relations + parsedStates := cloneStates(states) + for name, state := range states { + // avoid self removal + if lo.Contains(state.Remove, name) { + state.Remove = lo.Without(state.Remove, name) + parsedStates[name] = state + } + } m := &Machine{ ID: uuid.New().String(), HandlerTimeout: time.Second, - States: states, + States: parsedStates, clock: map[string]uint64{}, emitters: []*emitter{}, PrintExceptions: true, diff --git a/pkg/machine/misc.go b/pkg/machine/misc.go index 88a880c..4491ce1 100644 --- a/pkg/machine/misc.go +++ b/pkg/machine/misc.go @@ -322,3 +322,32 @@ func padString(str string, length int, pad string) string { } } } + +// cloneStates deep clones the states struct and returns a copy. +func cloneStates(states States) States { + ret := make(States) + for name, state := range states { + stateCopy := State{ + Auto: state.Auto, + Multi: state.Multi, + } + if state.Require != nil { + stateCopy.Require = make(S, len(state.Require)) + copy(stateCopy.Require, state.Require) + } + if state.Add != nil { + stateCopy.Add = make(S, len(state.Add)) + copy(stateCopy.Add, state.Add) + } + if state.Remove != nil { + stateCopy.Remove = make(S, len(state.Remove)) + copy(stateCopy.Remove, state.Remove) + } + if state.After != nil { + stateCopy.After = make(S, len(state.After)) + copy(stateCopy.After, state.After) + } + ret[name] = stateCopy + } + return ret +}