pointer.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. Copyright 2018 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 pointer
  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. // Int32Ptr returns a pointer to an int32
  43. func Int32Ptr(i int32) *int32 {
  44. return &i
  45. }
  46. // Int64Ptr returns a pointer to an int64
  47. func Int64Ptr(i int64) *int64 {
  48. return &i
  49. }
  50. // Int32PtrDerefOr dereference the int32 ptr and returns it i not nil,
  51. // else returns def.
  52. func Int32PtrDerefOr(ptr *int32, def int32) int32 {
  53. if ptr != nil {
  54. return *ptr
  55. }
  56. return def
  57. }
  58. // BoolPtr returns a pointer to a bool
  59. func BoolPtr(b bool) *bool {
  60. return &b
  61. }
  62. // StringPtr returns a pointer to the passed string.
  63. func StringPtr(s string) *string {
  64. return &s
  65. }
  66. // Float32Ptr returns a pointer to the passed float32.
  67. func Float32Ptr(i float32) *float32 {
  68. return &i
  69. }
  70. // Float64Ptr returns a pointer to the passed float64.
  71. func Float64Ptr(i float64) *float64 {
  72. return &i
  73. }