File: tool.go

package info (click to toggle)
gitlab-agent 16.11.5-1
  • links: PTS, VCS
  • area: contrib
  • in suites: experimental
  • size: 7,072 kB
  • sloc: makefile: 193; sh: 55; ruby: 3
file content (30 lines) | stat: -rw-r--r-- 875 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package tool

// TransformMap transforms map of type IN into a map of type OUT.
// The main point of this function is to optimize memory usage. It allocates a single slice for
// the elements in values of the map rather than a slice per key.
func TransformMap[K comparable, V1 any, V2 any, IN ~map[K]V1, OUT ~map[K]V2, E any](
	in IN,
	v1Len func(V1) int,
	appendV1ToSlice func(V1, []E) []E,
	elemToV2 func([]E) V2) OUT {

	if len(in) == 0 {
		return nil
	}

	result := make(OUT, len(in))
	valsLen := 0
	for _, v := range in {
		valsLen += v1Len(v)
	}
	vals := make([]E, 0, valsLen) // allocate backing array for all elements in one go
	for k, v := range in {
		vals = appendV1ToSlice(v, vals)
		// set capacity to length to protect against potential append overwriting next value
		lk := len(vals)
		result[k] = elemToV2(vals[:lk:lk])
		vals = vals[lk:]
	}
	return result
}