Debian Codegraph @

internal/dark/interface.go

raw
1 // Copyright (c) 2018, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package dark
8
9 import (
10 "reflect"
11
12 "github.com/maxatome/go-testdeep/internal/or"
13 "github.com/maxatome/go-testdeep/internal/spew"
14 )
15
16 // UnsafeDisabled is a build-time constant which specifies whether or
17 // not access to the unsafe package is available.
18 const UnsafeDisabled = spew.UnsafeDisabled
19
20 // GetInterface does its best to return the data behind val. If force
21 // is true, it tries to bypass golang protections using the unsafe
22 // package.
23 //
24 // It returns (nil, false) if the data behind val can not be retrieved
25 // as an any interface (aka struct private + non-copyable field).
26 var GetInterface = func(val reflect.Value, force bool) (any, bool) {
27 if !val.IsValid() {
28 return nil, true
29 }
30
31 if val.CanInterface() {
32 return val.Interface(), true
33 }
34
35 if force {
36 val = spew.UnsafeReflectValue(val)
37 if val.CanInterface() {
38 return val.Interface(), true
39 }
40 }
41
42 // For some types, we can copy them in new visitable reflect.Value instances
43 copyVal, ok := CopyValue(val)
44 if ok && copyVal.CanInterface() {
45 return copyVal.Interface(), true
46 }
47
48 // For others, in environments where "unsafe" package is not
49 // available, we cannot go further
50 return nil, false
51 }
52
53 // MustGetInterface does its best to return the data behind val. If it
54 // fails (struct private + non-copyable field), it panics.
55 func MustGetInterface(val reflect.Value) any {
56 ret, ok := GetInterface(val, true)
57 or.Panic(ok,
58 "dark.GetInterface() does not handle private ", val.Kind(), " kind")
59 return ret
60 }