File tree 2 files changed +75
-0
lines changed
2 files changed +75
-0
lines changed Original file line number Diff line number Diff line change
1
+ //go:build go1.18
2
+ // +build go1.18
3
+
4
+ /*
5
+ Copyright 2023 The Kubernetes Authors.
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
18
+ */
19
+
20
+ package klog
21
+
22
+ // SafePtr is a function that takes a pointer of any type (T) as an argument.
23
+ // If the provided pointer is not nil, it returns the same pointer. If it is nil, it returns nil instead.
24
+ //
25
+ // This function is particularly useful to prevent nil pointer dereferencing when:
26
+ //
27
+ // - The type implements interfaces that are called by the logger, such as `fmt.Stringer`.
28
+ // - And these interface implementations do not perform nil checks themselves.
29
+ func SafePtr [T any ](p * T ) any {
30
+ if p == nil {
31
+ return nil
32
+ }
33
+ return p
34
+ }
Original file line number Diff line number Diff line change
1
+ //go:build go1.18
2
+ // +build go1.18
3
+
4
+ /*
5
+ Copyright 2023 The Kubernetes Authors.
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
18
+ */
19
+
20
+ package klog_test
21
+
22
+ import (
23
+ "testing"
24
+
25
+ "k8s.io/klog/v2"
26
+ )
27
+
28
+ func TestSafePtr (t * testing.T ) {
29
+ // Test with nil pointer
30
+ var stringPtr * string
31
+ if result := klog .SafePtr (stringPtr ); result != nil {
32
+ t .Errorf ("Expected nil, got %p" , result )
33
+ }
34
+
35
+ // Test with non-nil pointer
36
+ expected := "foo"
37
+ stringPtr = & expected
38
+ if result := klog .SafePtr (stringPtr ); result != stringPtr {
39
+ t .Errorf ("Expected %v, got %v" , stringPtr , result )
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments