Commit e46acb09 authored by Russ Cox's avatar Russ Cox

reflect: add PtrTo, add Value.Addr (old Addr is now UnsafeAddr)

This change makes it possible to take the address of a
struct field or slice element in order to call a method that
requires a pointer receiver.

Existing code that uses the Value.Addr method will have
to change (as gob does in this CL) to call UnsafeAddr instead.

R=r, rog
CC=golang-dev
https://golang.org/cl/4239052
parent 44fd7573
...@@ -518,7 +518,7 @@ func (dec *Decoder) decodeArray(atyp *reflect.ArrayType, state *decodeState, p u ...@@ -518,7 +518,7 @@ func (dec *Decoder) decodeArray(atyp *reflect.ArrayType, state *decodeState, p u
func decodeIntoValue(state *decodeState, op decOp, indir int, v reflect.Value, ovfl os.ErrorString) reflect.Value { func decodeIntoValue(state *decodeState, op decOp, indir int, v reflect.Value, ovfl os.ErrorString) reflect.Value {
instr := &decInstr{op, 0, indir, 0, ovfl} instr := &decInstr{op, 0, indir, 0, ovfl}
up := unsafe.Pointer(v.Addr()) up := unsafe.Pointer(v.UnsafeAddr())
if indir > 1 { if indir > 1 {
up = decIndirect(up, indir) up = decIndirect(up, indir)
} }
...@@ -1052,9 +1052,9 @@ func (dec *Decoder) decodeValue(wireId typeId, val reflect.Value) (err os.Error) ...@@ -1052,9 +1052,9 @@ func (dec *Decoder) decodeValue(wireId typeId, val reflect.Value) (err os.Error)
name := base.Name() name := base.Name()
return os.ErrorString("gob: type mismatch: no fields matched compiling decoder for " + name) return os.ErrorString("gob: type mismatch: no fields matched compiling decoder for " + name)
} }
return dec.decodeStruct(engine, ut, uintptr(val.Addr()), indir) return dec.decodeStruct(engine, ut, uintptr(val.UnsafeAddr()), indir)
} }
return dec.decodeSingle(engine, ut, uintptr(val.Addr())) return dec.decodeSingle(engine, ut, uintptr(val.UnsafeAddr()))
} }
func (dec *Decoder) decodeIgnoredValue(wireId typeId) os.Error { func (dec *Decoder) decodeIgnoredValue(wireId typeId) os.Error {
......
...@@ -356,7 +356,7 @@ func encodeReflectValue(state *encoderState, v reflect.Value, op encOp, indir in ...@@ -356,7 +356,7 @@ func encodeReflectValue(state *encoderState, v reflect.Value, op encOp, indir in
if v == nil { if v == nil {
errorf("gob: encodeReflectValue: nil element") errorf("gob: encodeReflectValue: nil element")
} }
op(nil, state, unsafe.Pointer(v.Addr())) op(nil, state, unsafe.Pointer(v.UnsafeAddr()))
} }
func (enc *Encoder) encodeMap(b *bytes.Buffer, mv *reflect.MapValue, keyOp, elemOp encOp, keyIndir, elemIndir int) { func (enc *Encoder) encodeMap(b *bytes.Buffer, mv *reflect.MapValue, keyOp, elemOp encOp, keyIndir, elemIndir int) {
...@@ -575,9 +575,9 @@ func (enc *Encoder) encode(b *bytes.Buffer, value reflect.Value, ut *userTypeInf ...@@ -575,9 +575,9 @@ func (enc *Encoder) encode(b *bytes.Buffer, value reflect.Value, ut *userTypeInf
} }
engine := enc.lockAndGetEncEngine(ut.base) engine := enc.lockAndGetEncEngine(ut.base)
if value.Type().Kind() == reflect.Struct { if value.Type().Kind() == reflect.Struct {
enc.encodeStruct(b, engine, value.Addr()) enc.encodeStruct(b, engine, value.UnsafeAddr())
} else { } else {
enc.encodeSingle(b, engine, value.Addr()) enc.encodeSingle(b, engine, value.UnsafeAddr())
} }
return nil return nil
} }
...@@ -1093,6 +1093,18 @@ func TestMethod(t *testing.T) { ...@@ -1093,6 +1093,18 @@ func TestMethod(t *testing.T) {
t.Errorf("Value Method returned %d; want 250", i) t.Errorf("Value Method returned %d; want 250", i)
} }
// Curried method of pointer.
i = NewValue(&p).Method(0).Call([]Value{NewValue(10)})[0].(*IntValue).Get()
if i != 250 {
t.Errorf("Value Method returned %d; want 250", i)
}
// Curried method of pointer to value.
i = NewValue(p).Addr().Method(0).Call([]Value{NewValue(10)})[0].(*IntValue).Get()
if i != 250 {
t.Errorf("Value Method returned %d; want 250", i)
}
// Curried method of interface value. // Curried method of interface value.
// Have to wrap interface value in a struct to get at it. // Have to wrap interface value in a struct to get at it.
// Passing it to NewValue directly would // Passing it to NewValue directly would
...@@ -1390,3 +1402,66 @@ func TestEmbeddedMethods(t *testing.T) { ...@@ -1390,3 +1402,66 @@ func TestEmbeddedMethods(t *testing.T) {
t.Errorf("f(o) = %d, want 2", v) t.Errorf("f(o) = %d, want 2", v)
} }
} }
func TestPtrTo(t *testing.T) {
var i int
typ := Typeof(i)
for i = 0; i < 100; i++ {
typ = PtrTo(typ)
}
for i = 0; i < 100; i++ {
typ = typ.(*PtrType).Elem()
}
if typ != Typeof(i) {
t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, Typeof(i))
}
}
func TestAddr(t *testing.T) {
var p struct {
X, Y int
}
v := NewValue(&p)
v = v.(*PtrValue).Elem()
v = v.Addr()
v = v.(*PtrValue).Elem()
v = v.(*StructValue).Field(0)
v.(*IntValue).Set(2)
if p.X != 2 {
t.Errorf("Addr.Elem.Set failed to set value")
}
// Again but take address of the NewValue value.
// Exercises generation of PtrTypes not present in the binary.
v = NewValue(&p)
v = v.Addr()
v = v.(*PtrValue).Elem()
v = v.(*PtrValue).Elem()
v = v.Addr()
v = v.(*PtrValue).Elem()
v = v.(*StructValue).Field(0)
v.(*IntValue).Set(3)
if p.X != 3 {
t.Errorf("Addr.Elem.Set failed to set value")
}
// Starting without pointer we should get changed value
// in interface.
v = NewValue(p)
v0 := v
v = v.Addr()
v = v.(*PtrValue).Elem()
v = v.(*StructValue).Field(0)
v.(*IntValue).Set(4)
if p.X != 3 { // should be unchanged from last time
t.Errorf("somehow value Set changed original p")
}
p = v0.Interface().(struct {
X, Y int
})
if p.X != 4 {
t.Errorf("Addr.Elem.Set valued to set value in top value")
}
}
...@@ -31,8 +31,8 @@ func deepValueEqual(v1, v2 Value, visited map[uintptr]*visit, depth int) bool { ...@@ -31,8 +31,8 @@ func deepValueEqual(v1, v2 Value, visited map[uintptr]*visit, depth int) bool {
// if depth > 10 { panic("deepValueEqual") } // for debugging // if depth > 10 { panic("deepValueEqual") } // for debugging
addr1 := v1.Addr() addr1 := v1.UnsafeAddr()
addr2 := v2.Addr() addr2 := v2.UnsafeAddr()
if addr1 > addr2 { if addr1 > addr2 {
// Canonicalize order to reduce number of entries in visited. // Canonicalize order to reduce number of entries in visited.
addr1, addr2 = addr2, addr1 addr1, addr2 = addr2, addr1
......
...@@ -18,6 +18,7 @@ package reflect ...@@ -18,6 +18,7 @@ package reflect
import ( import (
"runtime" "runtime"
"strconv" "strconv"
"sync"
"unsafe" "unsafe"
) )
...@@ -251,6 +252,8 @@ type Type interface { ...@@ -251,6 +252,8 @@ type Type interface {
// NumMethods returns the number of methods in the type's method set. // NumMethods returns the number of methods in the type's method set.
NumMethod() int NumMethod() int
common() *commonType
uncommon() *uncommonType uncommon() *uncommonType
} }
...@@ -361,6 +364,8 @@ func (t *commonType) FieldAlign() int { return int(t.fieldAlign) } ...@@ -361,6 +364,8 @@ func (t *commonType) FieldAlign() int { return int(t.fieldAlign) }
func (t *commonType) Kind() Kind { return Kind(t.kind & kindMask) } func (t *commonType) Kind() Kind { return Kind(t.kind & kindMask) }
func (t *commonType) common() *commonType { return t }
func (t *uncommonType) Method(i int) (m Method) { func (t *uncommonType) Method(i int) (m Method) {
if t == nil || i < 0 || i >= len(t.methods) { if t == nil || i < 0 || i >= len(t.methods) {
return return
...@@ -374,7 +379,7 @@ func (t *uncommonType) Method(i int) (m Method) { ...@@ -374,7 +379,7 @@ func (t *uncommonType) Method(i int) (m Method) {
} }
m.Type = toType(*p.typ).(*FuncType) m.Type = toType(*p.typ).(*FuncType)
fn := p.tfn fn := p.tfn
m.Func = &FuncValue{value: value{m.Type, addr(&fn), true}} m.Func = &FuncValue{value: value{m.Type, addr(&fn), canSet}}
return return
} }
...@@ -689,3 +694,84 @@ type ArrayOrSliceType interface { ...@@ -689,3 +694,84 @@ type ArrayOrSliceType interface {
// Typeof returns the reflection Type of the value in the interface{}. // Typeof returns the reflection Type of the value in the interface{}.
func Typeof(i interface{}) Type { return toType(unsafe.Typeof(i)) } func Typeof(i interface{}) Type { return toType(unsafe.Typeof(i)) }
// ptrMap is the cache for PtrTo.
var ptrMap struct {
sync.RWMutex
m map[Type]*PtrType
}
// runtimePtrType is the runtime layout for a *PtrType.
// The memory immediately before the *PtrType is always
// the canonical runtime.Type to be used for a *runtime.Type
// describing this PtrType.
type runtimePtrType struct {
runtime.Type
runtime.PtrType
}
// PtrTo returns the pointer type with element t.
// For example, if t represents type Foo, PtrTo(t) represents *Foo.
func PtrTo(t Type) *PtrType {
// If t records its pointer-to type, use it.
ct := t.common()
if p := ct.ptrToThis; p != nil {
return toType(*p).(*PtrType)
}
// Otherwise, synthesize one.
// This only happens for pointers with no methods.
// We keep the mapping in a map on the side, because
// this operation is rare and a separate map lets us keep
// the type structures in read-only memory.
ptrMap.RLock()
if m := ptrMap.m; m != nil {
if p := m[t]; p != nil {
ptrMap.RUnlock()
return p
}
}
ptrMap.RUnlock()
ptrMap.Lock()
if ptrMap.m == nil {
ptrMap.m = make(map[Type]*PtrType)
}
p := ptrMap.m[t]
if p != nil {
// some other goroutine won the race and created it
ptrMap.Unlock()
return p
}
// runtime.Type value is always right before type structure.
// 2*ptrSize is size of interface header
rt := (*runtime.Type)(unsafe.Pointer(uintptr(unsafe.Pointer(ct)) - uintptr(unsafe.Sizeof(runtime.Type(nil)))))
rp := new(runtimePtrType)
rp.Type = &rp.PtrType
// initialize rp.PtrType using *byte's PtrType as a prototype.
// have to do assignment as PtrType, not runtime.PtrType,
// in order to write to unexported fields.
p = (*PtrType)(unsafe.Pointer(&rp.PtrType))
bp := (*PtrType)(unsafe.Pointer(unsafe.Typeof((*byte)(nil)).(*runtime.PtrType)))
*p = *bp
s := "*" + *ct.string
p.string = &s
// For the type structures linked into the binary, the
// compiler provides a good hash of the string.
// Create a good hash for the new string by using
// the FNV-1 hash's mixing function to combine the
// old hash and the new "*".
p.hash = ct.hash*16777619 ^ '*'
p.uncommonType = nil
p.ptrToThis = nil
p.elem = rt
ptrMap.m[t] = (*PtrType)(unsafe.Pointer(&rp.PtrType))
ptrMap.Unlock()
return p
}
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment