blob: c2b9d21b4c775c8c426982f1ab285b759995fee8 [file] [log] [blame]
Joe Tsaifa02f4e2018-09-12 16:20:37 -07001// 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
7package impl
8
9import (
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.
16type offset uintptr
17
18// offsetOf returns a field offset for the struct field.
19func offsetOf(f reflect.StructField) offset {
20 return offset(f.Offset)
21}
22
23// pointer is a pointer to a message struct or field.
24type pointer struct{ p unsafe.Pointer }
25
26// pointerOfValue returns v as a pointer.
27func pointerOfValue(v reflect.Value) pointer {
28 return pointer{p: unsafe.Pointer(v.Pointer())}
29}
30
Joe Tsaic6b75612018-09-13 14:24:37 -070031// pointerOfIface returns the pointer portion of an interface.
32func 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 Tsaifa02f4e2018-09-12 16:20:37 -070040// 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.
42func (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.
47func (p pointer) asType(t reflect.Type) reflect.Value {
48 return reflect.NewAt(t, p.p)
49}