github.com/kubernetes/utils@v0.0.0-20190308190857-21c4ce38f2a7/pointer/pointer.go (about) 1 /* 2 Copyright 2018 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package pointer 18 19 import ( 20 "fmt" 21 "reflect" 22 ) 23 24 // AllPtrFieldsNil tests whether all pointer fields in a struct are nil. This is useful when, 25 // for example, an API struct is handled by plugins which need to distinguish 26 // "no plugin accepted this spec" from "this spec is empty". 27 // 28 // This function is only valid for structs and pointers to structs. Any other 29 // type will cause a panic. Passing a typed nil pointer will return true. 30 func AllPtrFieldsNil(obj interface{}) bool { 31 v := reflect.ValueOf(obj) 32 if !v.IsValid() { 33 panic(fmt.Sprintf("reflect.ValueOf() produced a non-valid Value for %#v", obj)) 34 } 35 if v.Kind() == reflect.Ptr { 36 if v.IsNil() { 37 return true 38 } 39 v = v.Elem() 40 } 41 for i := 0; i < v.NumField(); i++ { 42 if v.Field(i).Kind() == reflect.Ptr && !v.Field(i).IsNil() { 43 return false 44 } 45 } 46 return true 47 } 48 49 // Int32Ptr returns a pointer to an int32 50 func Int32Ptr(i int32) *int32 { 51 return &i 52 } 53 54 // Int64Ptr returns a pointer to an int64 55 func Int64Ptr(i int64) *int64 { 56 return &i 57 } 58 59 // Int32PtrDerefOr dereference the int32 ptr and returns it i not nil, 60 // else returns def. 61 func Int32PtrDerefOr(ptr *int32, def int32) int32 { 62 if ptr != nil { 63 return *ptr 64 } 65 return def 66 } 67 68 // BoolPtr returns a pointer to a bool 69 func BoolPtr(b bool) *bool { 70 return &b 71 } 72 73 // StringPtr returns a pointer to the passed string. 74 func StringPtr(s string) *string { 75 return &s 76 } 77 78 // Float32Ptr returns a pointer to the passed float32. 79 func Float32Ptr(i float32) *float32 { 80 return &i 81 } 82 83 // Float64Ptr returns a pointer to the passed float64. 84 func Float64Ptr(i float64) *float64 { 85 return &i 86 }