File: interface.go

package info (click to toggle)
golang-github-maxatome-go-testdeep 1.14.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,416 kB
  • sloc: perl: 1,012; yacc: 130; makefile: 2
file content (55 lines) | stat: -rw-r--r-- 1,438 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Copyright (c) 2018, Maxime Soulé
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.

package dark

import (
	"reflect"
)

// GetInterface does its best to return the data behind val. If force
// is true, it tries to bypass golang protections using the unsafe
// package.
//
// It returns (nil, false) if the data behind val can not be retrieved
// as an any interface (aka struct private + non-copyable field).
var GetInterface = func(val reflect.Value, force bool) (any, bool) {
	if !val.IsValid() {
		return nil, true
	}

	if val.CanInterface() {
		return val.Interface(), true
	}

	if force {
		val = unsafeReflectValue(val)
		if val.CanInterface() {
			return val.Interface(), true
		}
	}

	// For some types, we can copy them in new visitable reflect.Value instances
	copyVal, ok := CopyValue(val)
	if ok && copyVal.CanInterface() {
		return copyVal.Interface(), true
	}

	// For others, in environments where "unsafe" package is not
	// available, we cannot go further
	return nil, false
}

// MustGetInterface does its best to return the data behind val. If it
// fails (struct private + non-copyable field), it panics.
func MustGetInterface(val reflect.Value) any {
	ret, ok := GetInterface(val, true)
	if ok {
		return ret
	}
	panic("dark.GetInterface() does not handle private " +
		val.Kind().String() + " kind")
}