export_unsafe.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  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. // +build !purego
  5. package cmp
  6. import (
  7. "reflect"
  8. "unsafe"
  9. )
  10. const supportExporters = true
  11. // retrieveUnexportedField uses unsafe to forcibly retrieve any field from
  12. // a struct such that the value has read-write permissions.
  13. //
  14. // The parent struct, v, must be addressable, while f must be a StructField
  15. // describing the field to retrieve. If addr is false,
  16. // then the returned value will be shallowed copied to be non-addressable.
  17. func retrieveUnexportedField(v reflect.Value, f reflect.StructField, addr bool) reflect.Value {
  18. ve := reflect.NewAt(f.Type, unsafe.Pointer(uintptr(unsafe.Pointer(v.UnsafeAddr()))+f.Offset)).Elem()
  19. if !addr {
  20. // A field is addressable if and only if the struct is addressable.
  21. // If the original parent value was not addressable, shallow copy the
  22. // value to make it non-addressable to avoid leaking an implementation
  23. // detail of how forcibly exporting a field works.
  24. if ve.Kind() == reflect.Interface && ve.IsNil() {
  25. return reflect.Zero(f.Type)
  26. }
  27. return reflect.ValueOf(ve.Interface()).Convert(f.Type)
  28. }
  29. return ve
  30. }