blob: f7bd95a327a1fa36f838d48db6d03a1facafa643 [file] [log] [blame]
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package state
import (
"fmt"
"go.starlark.net/starlark"
)
// The key used to read and store state from a starlark.Thread.
const threadStateKey = "fxicfg_state_key"
// SetThreadState stores State inside a starlark.Thread.
func SetThreadState(th *starlark.Thread, state State) {
th.SetLocal(threadStateKey, state)
}
// GetThreadState reads a State from a starlark.Thread.
func GetThreadState(th *starlark.Thread) (State, error) {
state, ok := th.Local(threadStateKey).(State)
if !ok {
return State{}, fmt.Errorf("thread %q has no key %q", th.Name, threadStateKey)
}
return state, nil
}
// ThreadModifier passes state information between starlark.Thread objects. This is
// primarily used by the generator as a LUCI interpreter hook.
type ThreadModifier State
// State returns the state held by this ThreadModifier.
func (t ThreadModifier) State() State {
return State(t)
}
// WriteTo stores this ThreadModifier's state in the given starlark.Thread.
func (t ThreadModifier) WriteTo(th *starlark.Thread) {
SetThreadState(th, State(t))
}
// ReadFrom updates this ThreadModifier's state to match given starlark.Thread's.
func (t *ThreadModifier) ReadFrom(th *starlark.Thread) error {
state, err := GetThreadState(th)
if err != nil {
return err
}
*t = ThreadModifier(state)
return nil
}