1// Copyright 2017, The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5//go:build !purego 6// +build !purego 7 8package cmp 9 10import ( 11 "reflect" 12 "unsafe" 13) 14 15const supportExporters = true 16 17// retrieveUnexportedField uses unsafe to forcibly retrieve any field from 18// a struct such that the value has read-write permissions. 19// 20// The parent struct, v, must be addressable, while f must be a StructField 21// describing the field to retrieve. If addr is false, 22// then the returned value will be shallowed copied to be non-addressable. 23func retrieveUnexportedField(v reflect.Value, f reflect.StructField, addr bool) reflect.Value { 24 ve := reflect.NewAt(f.Type, unsafe.Pointer(uintptr(unsafe.Pointer(v.UnsafeAddr()))+f.Offset)).Elem() 25 if !addr { 26 // A field is addressable if and only if the struct is addressable. 27 // If the original parent value was not addressable, shallow copy the 28 // value to make it non-addressable to avoid leaking an implementation 29 // detail of how forcibly exporting a field works. 30 if ve.Kind() == reflect.Interface && ve.IsNil() { 31 return reflect.Zero(f.Type) 32 } 33 return reflect.ValueOf(ve.Interface()).Convert(f.Type) 34 } 35 return ve 36} 37