45 lines
946 B
Go
45 lines
946 B
Go
package data
|
|
|
|
import (
|
|
"bytes"
|
|
"sort"
|
|
)
|
|
|
|
// Data saves slices of bytes referenced by labels.
|
|
type Data map[string][]byte
|
|
|
|
// Finalize returns the final raw data slice and a map of labels with their respective indices.
|
|
// It will try to reuse existing data whenever possible.
|
|
func (data Data) Finalize() ([]byte, map[string]int32) {
|
|
var (
|
|
final []byte
|
|
keys = make([]string, 0, len(data))
|
|
positions = make(map[string]int32, len(data))
|
|
)
|
|
|
|
for key := range data {
|
|
keys = append(keys, key)
|
|
}
|
|
|
|
sort.SliceStable(keys, func(i, j int) bool {
|
|
return len(data[keys[i]]) > len(data[keys[j]])
|
|
})
|
|
|
|
for _, key := range keys {
|
|
raw := data[key]
|
|
position := bytes.Index(final, raw)
|
|
|
|
if position != -1 {
|
|
positions[key] = int32(position)
|
|
} else {
|
|
positions[key] = int32(len(final))
|
|
final = append(final, raw...)
|
|
}
|
|
}
|
|
|
|
return final, positions
|
|
}
|
|
|
|
func (data Data) Insert(label string, raw []byte) {
|
|
data[label] = raw
|
|
}
|