blob: 72b782c26f609b47e8d39ef90e168aad5c300c33 [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
Joe Tsaibc534a92018-12-18 16:07:48 -08005// +build purego appengine
Joe Tsaifa02f4e2018-09-12 16:20:37 -07006
7package impl
8
9import (
10 "fmt"
11 "reflect"
12)
13
14// offset represents the offset to a struct field, accessible from a pointer.
15// The offset is the field index into a struct.
16type offset []int
17
18// offsetOf returns a field offset for the struct field.
19func offsetOf(f reflect.StructField) offset {
20 if len(f.Index) != 1 {
21 panic("embedded structs are not supported")
22 }
23 return f.Index
24}
25
26// pointer is an abstract representation of a pointer to a struct or field.
27type pointer struct{ v reflect.Value }
28
29// pointerOfValue returns v as a pointer.
30func pointerOfValue(v reflect.Value) pointer {
31 return pointer{v: v}
32}
33
Joe Tsaic6b75612018-09-13 14:24:37 -070034// pointerOfIface returns the pointer portion of an interface.
Joe Tsai6cf80c42018-12-01 04:57:09 -080035func pointerOfIface(v interface{}) pointer {
36 return pointer{v: reflect.ValueOf(v)}
Joe Tsaic6b75612018-09-13 14:24:37 -070037}
38
Joe Tsai6cf80c42018-12-01 04:57:09 -080039// IsNil reports whether the pointer is nil.
40func (p pointer) IsNil() bool {
41 return p.v.IsNil()
42}
43
44// Apply adds an offset to the pointer to derive a new pointer
Joe Tsaifa02f4e2018-09-12 16:20:37 -070045// to a specified field. The current pointer must be pointing at a struct.
Joe Tsai6cf80c42018-12-01 04:57:09 -080046func (p pointer) Apply(f offset) pointer {
Joe Tsaifa02f4e2018-09-12 16:20:37 -070047 // TODO: Handle unexported fields in an API that hides XXX fields?
48 return pointer{v: p.v.Elem().FieldByIndex(f).Addr()}
49}
50
Joe Tsai6cf80c42018-12-01 04:57:09 -080051// AsValueOf treats p as a pointer to an object of type t and returns the value.
52// It is equivalent to reflect.ValueOf(p.AsIfaceOf(t))
53func (p pointer) AsValueOf(t reflect.Type) reflect.Value {
Damien Neil927aaba2019-05-09 12:18:44 -070054 if got := p.v.Type().Elem(); got != t {
55 panic(fmt.Sprintf("invalid type: got %v, want %v", got, t))
Joe Tsaifa02f4e2018-09-12 16:20:37 -070056 }
57 return p.v
58}
Joe Tsai6cf80c42018-12-01 04:57:09 -080059
60// AsIfaceOf treats p as a pointer to an object of type t and returns the value.
61// It is equivalent to p.AsValueOf(t).Interface()
62func (p pointer) AsIfaceOf(t reflect.Type) interface{} {
63 return p.AsValueOf(t).Interface()
64}