master
go 38 lines 1.08 KB
Raw
1 // Unless explicitly stated otherwise all files in this repository are licensed
2 // under the Apache License Version 2.0.
3 // This product includes software developed at Datadog (https://www.datadoghq.com/).
4 // Copyright 2024-present Datadog, Inc.
5
6 package ddprofiledefinition
7
8 // cloneable is a generic type for objects that can duplicate themselves.
9 // It is exclusively used in the form [T cloneable[T]], i.e. a type that
10 // has a .Clone() that returns a new instance of itself.
11 type cloneable[T any] interface {
12 Clone() T
13 }
14
15 // CloneSlice clones all the objects in a slice into a new slice.
16 func cloneSlice[Slice ~[]T, T cloneable[T]](s Slice) Slice {
17 if s == nil {
18 return nil
19 }
20 result := make(Slice, 0, len(s))
21 for _, v := range s {
22 result = append(result, v.Clone())
23 }
24 return result
25 }
26
27 // CloneMap clones a map[K]T for any cloneable type T.
28 // The map keys are shallow-copied; values are cloned.
29 func cloneMap[Map ~map[K]T, K comparable, T cloneable[T]](m Map) Map {
30 if m == nil {
31 return nil
32 }
33 result := make(Map, len(m))
34 for k, v := range m {
35 result[k] = v.Clone()
36 }
37 return result
38 }