Debian Codegraph @

analysis/facts/nilness/testdata/src/example.com/Nilness/Nilness_go118.go

raw
1 //go:build go1.18
2
3 package pkg
4
5 // Make sure we don't crash upon seeing a MultiConvert instruction.
6 func generic1[T []byte | string](s T) T {
7 switch v := any(s).(type) {
8 case string:
9 return T(v)
10 case []byte:
11 return T(v)
12 default:
13 return s
14 }
15 }
16
17 // Make sure we don't emit a fact for a function whose return type isn't pointer-like.
18 func generic2[T [4]byte | string](s T) T {
19 switch v := any(s).(type) {
20 case string:
21 return T([]byte(v))
22 case [4]byte:
23 return T(v[:])
24 default:
25 return s
26 }
27 }
28
29 // Make sure we detect that the return value cannot be nil. It is either a string, a
30 // non-nil slice we got passed, or a non-nil slice we allocate. Note that we don't
31 // understand that the switch's non-default branches are exhaustive over the type set and
32 // for the fact to be computed, we have to return something non-nil from the unreachable
33 // default branch.
34 func generic3[T []byte | string](s T) T { // want generic3:`never returns nil: \[never\]`
35 switch v := any(s).(type) {
36 case string:
37 return T(v)
38 case []byte:
39 if v == nil {
40 return T([]byte{})
41 } else {
42 return T(v)
43 }
44 default:
45 return T([]byte{})
46 }
47 }