tile38/internal/collection/fields.go

90 lines
1.8 KiB
Go
Raw Permalink Normal View History

2019-02-15 18:26:55 +03:00
package collection
2019-02-15 18:47:27 +03:00
import (
"sync"
2019-02-15 18:26:55 +03:00
2019-02-15 18:47:27 +03:00
"github.com/tidwall/tile38/internal/collection/item"
)
2019-02-15 18:26:55 +03:00
// Fields ...
type Fields struct {
2019-02-15 18:47:27 +03:00
mu sync.Mutex
unpacked bool // fields have been unpacked
values []float64 // unpacked values
item *item.Item // base item
}
func (fields *Fields) unpack() {
if fields.unpacked {
return
}
fields.values = nil
fields.item.ForEachField(-1, func(value float64) bool {
fields.values = append(fields.values, value)
return true
})
fields.unpacked = true
2019-02-15 18:26:55 +03:00
}
// ForEach iterates over each field. The count param is the number of
// iterations. When count is less than zero, then all fields are returns.
func (fields *Fields) ForEach(count int, iter func(value float64) bool) {
if fields == nil || fields.item == nil {
return
}
2019-02-16 00:02:04 +03:00
if !fields.item.Packed() {
2019-02-15 18:47:27 +03:00
fields.item.ForEachField(count, iter)
return
}
// packed values
fields.mu.Lock()
defer fields.mu.Unlock()
if !fields.unpacked {
fields.unpack()
}
var n int
if count < 0 {
n = len(fields.values)
} else {
n = count
}
for i := 0; i < n; i++ {
var field float64
if i < len(fields.values) {
field = fields.values[i]
}
if !iter(field) {
return
}
}
2019-02-15 18:26:55 +03:00
}
// Get returns the value for a field at index. If there is no field at index,
// then zero is returned.
func (fields *Fields) Get(index int) float64 {
if fields == nil || fields.item == nil {
return 0
}
2019-02-16 00:02:04 +03:00
if !fields.item.Packed() {
2019-02-15 18:47:27 +03:00
return fields.item.GetField(index)
}
// packed values
fields.mu.Lock()
if !fields.unpacked {
fields.unpack()
}
var value float64
if index < len(fields.values) {
value = fields.values[index]
}
fields.mu.Unlock()
return value
2019-02-15 18:26:55 +03:00
}
func itemFields(item *item.Item) *Fields {
if item == nil || !item.HasFields() {
return nil
}
return &Fields{item: item}
}