Don't copy LatestMap if merging a subset

This commit is contained in:
Bryan Boreham
2018-06-29 08:10:48 +00:00
parent a06d82ccf8
commit 43a0a7e5d3
2 changed files with 78 additions and 15 deletions

View File

@@ -74,8 +74,9 @@ function generate_latest_map() {
return len(m)
}
// Merge produces a fresh ${latest_map_type} containing the keys from both inputs.
// Merge produces a ${latest_map_type} containing the keys from both inputs.
// When both inputs contain the same key, the newer value is used.
// Tries to return one of its inputs, if that already holds the correct result.
func (m ${latest_map_type}) Merge(n ${latest_map_type}) ${latest_map_type} {
switch {
case m == nil:
@@ -83,13 +84,33 @@ function generate_latest_map() {
case n == nil:
return m
}
l := len(m)
if len(n) > l {
l = len(n)
if len(n) > len(m) {
m, n = n, m //swap so m is always at least as long as n
}
out := make([]${entry_type}, 0, l)
i, j := 0, 0
loop:
for i < len(m) {
switch {
case j >= len(n) || m[i].key < n[j].key:
i++
case m[i].key == n[j].key:
if m[i].Timestamp.Before(n[j].Timestamp) {
break loop
}
i++
j++
default:
break loop
}
}
if i >= len(m) && j >= len(n) {
return m
}
out := make([]${entry_type}, i, len(m))
copy(out, m[:i])
for i < len(m) {
switch {
case j >= len(n) || m[i].key < n[j].key: