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 | "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. |
| 16 | type offset []int |
| 17 | |
| 18 | // offsetOf returns a field offset for the struct field. |
| 19 | func 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. |
| 27 | type pointer struct{ v reflect.Value } |
| 28 | |
| 29 | // pointerOfValue returns v as a pointer. |
| 30 | func pointerOfValue(v reflect.Value) pointer { |
| 31 | return pointer{v: v} |
| 32 | } |
| 33 | |
| 34 | // apply adds an offset to the pointer to derive a new pointer |
| 35 | // to a specified field. The current pointer must be pointing at a struct. |
| 36 | func (p pointer) apply(f offset) pointer { |
| 37 | // TODO: Handle unexported fields in an API that hides XXX fields? |
| 38 | return pointer{v: p.v.Elem().FieldByIndex(f).Addr()} |
| 39 | } |
| 40 | |
| 41 | // asType treats p as a pointer to an object of type t and returns the value. |
| 42 | func (p pointer) asType(t reflect.Type) reflect.Value { |
| 43 | if p.v.Type().Elem() != t { |
| 44 | panic(fmt.Sprintf("invalid type: got %v, want %v", p.v.Type(), t)) |
| 45 | } |
| 46 | return p.v |
| 47 | } |