/ pkg / ptr / ptr.go
ptr.go
 1  /*
 2  Copyright 2023 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 ptr
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  // To returns a pointer to the given value.
50  func To[T any](v T) *T {
51  	return &v
52  }
53  
54  // Deref dereferences ptr and returns the value it points to if no nil, or else
55  // returns def.
56  func Deref[T any](ptr *T, def T) T {
57  	if ptr != nil {
58  		return *ptr
59  	}
60  	return def
61  }
62  
63  // Equal returns true if both arguments are nil or both arguments
64  // dereference to the same value.
65  func Equal[T comparable](a, b *T) bool {
66  	if (a == nil) != (b == nil) {
67  		return false
68  	}
69  	if a == nil {
70  		return true
71  	}
72  	return *a == *b
73  }