ptr.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. Copyright 2023 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package ptr
  14. import (
  15. "fmt"
  16. "reflect"
  17. )
  18. // AllPtrFieldsNil tests whether all pointer fields in a struct are nil. This is useful when,
  19. // for example, an API struct is handled by plugins which need to distinguish
  20. // "no plugin accepted this spec" from "this spec is empty".
  21. //
  22. // This function is only valid for structs and pointers to structs. Any other
  23. // type will cause a panic. Passing a typed nil pointer will return true.
  24. func AllPtrFieldsNil(obj interface{}) bool {
  25. v := reflect.ValueOf(obj)
  26. if !v.IsValid() {
  27. panic(fmt.Sprintf("reflect.ValueOf() produced a non-valid Value for %#v", obj))
  28. }
  29. if v.Kind() == reflect.Ptr {
  30. if v.IsNil() {
  31. return true
  32. }
  33. v = v.Elem()
  34. }
  35. for i := 0; i < v.NumField(); i++ {
  36. if v.Field(i).Kind() == reflect.Ptr && !v.Field(i).IsNil() {
  37. return false
  38. }
  39. }
  40. return true
  41. }
  42. // To returns a pointer to the given value.
  43. func To[T any](v T) *T {
  44. return &v
  45. }
  46. // Deref dereferences ptr and returns the value it points to if no nil, or else
  47. // returns def.
  48. func Deref[T any](ptr *T, def T) T {
  49. if ptr != nil {
  50. return *ptr
  51. }
  52. return def
  53. }
  54. // Equal returns true if both arguments are nil or both arguments
  55. // dereference to the same value.
  56. func Equal[T comparable](a, b *T) bool {
  57. if (a == nil) != (b == nil) {
  58. return false
  59. }
  60. if a == nil {
  61. return true
  62. }
  63. return *a == *b
  64. }