helper/schema: Move computedKeys init to init function

This simplifies the new value initialization and future-proofs it
against more complex initialization functionality.
This commit is contained in:
Chris Marchesi 2017-05-31 10:02:25 -07:00 committed by Martin Atkins
parent f0aafe4d67
commit 9625830980
1 changed files with 13 additions and 9 deletions

View File

@ -22,6 +22,16 @@ type newValueWriter struct {
// A lock to prevent races on writes. The underlying writer will have one as // A lock to prevent races on writes. The underlying writer will have one as
// well - this is for computed keys. // well - this is for computed keys.
lock sync.Mutex lock sync.Mutex
// To be used with init.
once sync.Once
}
// init performs any initialization tasks for the newValueWriter.
func (w *newValueWriter) init() {
if w.computedKeys == nil {
w.computedKeys = make(map[string]bool)
}
} }
// WriteField overrides MapValueWriter's WriteField, adding the ability to flag // WriteField overrides MapValueWriter's WriteField, adding the ability to flag
@ -37,12 +47,10 @@ func (w *newValueWriter) WriteField(address []string, value interface{}, compute
return err return err
} }
w.once.Do(w.init)
w.lock.Lock() w.lock.Lock()
defer w.lock.Unlock() defer w.lock.Unlock()
if w.computedKeys == nil {
w.computedKeys = make(map[string]bool)
}
if computed { if computed {
w.computedKeys[strings.Join(address, ".")] = true w.computedKeys[strings.Join(address, ".")] = true
} }
@ -51,11 +59,7 @@ func (w *newValueWriter) WriteField(address []string, value interface{}, compute
// ComputedKeysMap returns the underlying computed keys map. // ComputedKeysMap returns the underlying computed keys map.
func (w *newValueWriter) ComputedKeysMap() map[string]bool { func (w *newValueWriter) ComputedKeysMap() map[string]bool {
w.lock.Lock() w.once.Do(w.init)
defer w.lock.Unlock()
if w.computedKeys == nil {
w.computedKeys = make(map[string]bool)
}
return w.computedKeys return w.computedKeys
} }