Joe Tsai | fa02f4e | 2018-09-12 16:20:37 -0700 | [diff] [blame] | 1 | // Copyright 2018 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 | // +build !purego |
| 6 | |
| 7 | package impl |
| 8 | |
| 9 | import ( |
| 10 | "reflect" |
| 11 | "unsafe" |
| 12 | ) |
| 13 | |
| 14 | // offset represents the offset to a struct field, accessible from a pointer. |
| 15 | // The offset is the byte offset to the field from the start of the struct. |
| 16 | type offset uintptr |
| 17 | |
| 18 | // offsetOf returns a field offset for the struct field. |
| 19 | func offsetOf(f reflect.StructField) offset { |
| 20 | return offset(f.Offset) |
| 21 | } |
| 22 | |
| 23 | // pointer is a pointer to a message struct or field. |
| 24 | type pointer struct{ p unsafe.Pointer } |
| 25 | |
| 26 | // pointerOfValue returns v as a pointer. |
| 27 | func pointerOfValue(v reflect.Value) pointer { |
| 28 | return pointer{p: unsafe.Pointer(v.Pointer())} |
| 29 | } |
| 30 | |
Joe Tsai | c6b7561 | 2018-09-13 14:24:37 -0700 | [diff] [blame] | 31 | // pointerOfIface returns the pointer portion of an interface. |
| 32 | func pointerOfIface(v *interface{}) pointer { |
| 33 | type ifaceHeader struct { |
| 34 | Type unsafe.Pointer |
| 35 | Data unsafe.Pointer |
| 36 | } |
| 37 | return pointer{p: (*ifaceHeader)(unsafe.Pointer(v)).Data} |
| 38 | } |
| 39 | |
Joe Tsai | fa02f4e | 2018-09-12 16:20:37 -0700 | [diff] [blame] | 40 | // apply adds an offset to the pointer to derive a new pointer |
| 41 | // to a specified field. The current pointer must be pointing at a struct. |
| 42 | func (p pointer) apply(f offset) pointer { |
| 43 | return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))} |
| 44 | } |
| 45 | |
| 46 | // asType treats p as a pointer to an object of type t and returns the value. |
| 47 | func (p pointer) asType(t reflect.Type) reflect.Value { |
| 48 | return reflect.NewAt(t, p.p) |
| 49 | } |