You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.2 KiB

1 year ago
  1. package genutils
  2. type hasValid interface {
  3. Valid() bool
  4. }
  5. func ApplyUpdate[T any](dst *T, value *T) {
  6. if value != nil {
  7. *dst = *value
  8. }
  9. }
  10. func ApplyUpdateValid[T hasValid](dst *T, value *T) {
  11. if value != nil && (*value).Valid() {
  12. *dst = *value
  13. }
  14. }
  15. func ApplyUpdateNonZero[T comparable](dst *T, value *T) {
  16. var zero T
  17. if value != nil && *value != zero {
  18. *dst = *value
  19. }
  20. }
  21. func ApplyUpdateNilZero[T comparable](dst **T, value *T) {
  22. if value != nil {
  23. var zero T
  24. if *value == zero {
  25. *dst = nil
  26. } else {
  27. valueCopy := *value
  28. *dst = &valueCopy
  29. }
  30. }
  31. }
  32. func ApplyMapUpdate[K comparable, V any](dst *map[K]V, src map[K]*V) {
  33. if *dst == nil {
  34. dst = &map[K]V{}
  35. }
  36. for key, value := range src {
  37. if value != nil {
  38. (*dst)[key] = *value
  39. } else {
  40. delete(*dst, key)
  41. }
  42. }
  43. }
  44. func ApplyUpdateMapNilZero[K comparable, V comparable](dst *map[K]V, src map[K]V) {
  45. var zero V
  46. if *dst == nil {
  47. dst = &map[K]V{}
  48. }
  49. for key, value := range src {
  50. if value != zero {
  51. (*dst)[key] = value
  52. } else {
  53. delete(*dst, key)
  54. }
  55. }
  56. }
  57. func ApplyArrayUpdate[T comparable](arr *[]T, upsert []T, remove []T) {
  58. *arr = make([]T, 0, len(*arr)+len(upsert))
  59. *arr = UpsertIntoArray(*arr, upsert...)
  60. *arr = RemoveFromArray(*arr, remove...)
  61. }