github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/states/statemgr/transient_inmem.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package statemgr
     5  
     6  import (
     7  	"sync"
     8  
     9  	"github.com/terramate-io/tf/states"
    10  )
    11  
    12  // NewTransientInMemory returns a Transient implementation that retains
    13  // transient snapshots only in memory, as part of the object.
    14  //
    15  // The given initial state, if any, must not be modified concurrently while
    16  // this function is running, but may be freely modified once this function
    17  // returns without affecting the stored transient snapshot.
    18  func NewTransientInMemory(initial *states.State) Transient {
    19  	return &transientInMemory{
    20  		current: initial.DeepCopy(),
    21  	}
    22  }
    23  
    24  type transientInMemory struct {
    25  	lock    sync.RWMutex
    26  	current *states.State
    27  }
    28  
    29  var _ Transient = (*transientInMemory)(nil)
    30  
    31  func (m *transientInMemory) State() *states.State {
    32  	m.lock.RLock()
    33  	defer m.lock.RUnlock()
    34  
    35  	return m.current.DeepCopy()
    36  }
    37  
    38  func (m *transientInMemory) WriteState(new *states.State) error {
    39  	m.lock.Lock()
    40  	defer m.lock.Unlock()
    41  
    42  	m.current = new.DeepCopy()
    43  	return nil
    44  }