2022-01-06 06:40:23 -05:00
|
|
|
package helpers
|
|
|
|
|
|
|
|
|
|
import (
|
2022-01-26 17:23:55 -05:00
|
|
|
"net/http"
|
2023-04-23 11:43:50 +00:00
|
|
|
"net/netip"
|
2022-01-06 06:40:23 -05:00
|
|
|
)
|
|
|
|
|
|
2023-05-20 20:37:23 +00:00
|
|
|
func MergeWithPointer[T any](existing, other *T) (result *T) {
|
2022-01-06 06:40:23 -05:00
|
|
|
if existing != nil {
|
|
|
|
|
return existing
|
|
|
|
|
} else if other == nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
2023-05-20 20:37:23 +00:00
|
|
|
result = new(T)
|
2022-01-06 06:40:23 -05:00
|
|
|
*result = *other
|
|
|
|
|
return result
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func MergeWithString(existing, other string) (result string) {
|
|
|
|
|
if existing != "" {
|
|
|
|
|
return existing
|
|
|
|
|
}
|
|
|
|
|
return other
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-20 20:37:23 +00:00
|
|
|
func MergeWithNumber[T Number](existing, other T) (result T) { //nolint:ireturn
|
2022-06-12 14:03:00 +00:00
|
|
|
if existing != 0 {
|
|
|
|
|
return existing
|
|
|
|
|
}
|
|
|
|
|
return other
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-20 19:58:18 +00:00
|
|
|
func MergeWithIP(existing, other netip.Addr) (result netip.Addr) {
|
|
|
|
|
if existing.IsValid() {
|
2022-01-06 06:40:23 -05:00
|
|
|
return existing
|
2022-07-28 21:55:10 +00:00
|
|
|
}
|
|
|
|
|
return other
|
|
|
|
|
}
|
|
|
|
|
|
2022-01-26 17:23:55 -05:00
|
|
|
func MergeWithHTTPHandler(existing, other http.Handler) (result http.Handler) {
|
|
|
|
|
if existing != nil {
|
|
|
|
|
return existing
|
|
|
|
|
}
|
|
|
|
|
return other
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-20 20:37:23 +00:00
|
|
|
func MergeSlices[T comparable](a, b []T) (result []T) {
|
2022-01-06 06:40:23 -05:00
|
|
|
if a == nil && b == nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-20 20:37:23 +00:00
|
|
|
seen := make(map[T]struct{}, len(a)+len(b))
|
|
|
|
|
result = make([]T, 0, len(a)+len(b))
|
2022-01-06 06:40:23 -05:00
|
|
|
for _, s := range a {
|
|
|
|
|
if _, ok := seen[s]; ok {
|
|
|
|
|
continue // duplicate
|
|
|
|
|
}
|
|
|
|
|
result = append(result, s)
|
|
|
|
|
seen[s] = struct{}{}
|
|
|
|
|
}
|
|
|
|
|
for _, s := range b {
|
|
|
|
|
if _, ok := seen[s]; ok {
|
|
|
|
|
continue // duplicate
|
|
|
|
|
}
|
|
|
|
|
result = append(result, s)
|
|
|
|
|
seen[s] = struct{}{}
|
|
|
|
|
}
|
|
|
|
|
return result
|
|
|
|
|
}
|