New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(method): support method in definition #211
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
/* | ||
Copyright 2018 Caicloud Authors | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package method | ||
|
||
import ( | ||
"fmt" | ||
"reflect" | ||
"sync" | ||
) | ||
|
||
var defaultContainer = NewContainer() | ||
|
||
// Put puts an instance in this container. The instance must have one or more methods. | ||
func Put(instance interface{}) { | ||
defaultContainer.Put(instance) | ||
} | ||
|
||
// PutInterface puts an instance in this container. The instance must have one or more methods. | ||
// The iface should be like (*ArbitraryInterface)(nil). | ||
func PutInterface(iface interface{}, instance interface{}) { | ||
defaultContainer.PutInterface(iface, instance) | ||
} | ||
|
||
// Get returns a function for specified method. If you want to specify a method from an | ||
// interface, you need to use (*ArbitraryInterface)(nil) as instance. | ||
func Get(instance interface{}, method string) interface{} { | ||
return defaultContainer.Get(instance, method) | ||
} | ||
|
||
// Container contains instances and mappings. | ||
type Container struct { | ||
instances map[reflect.Type]interface{} | ||
lock sync.RWMutex | ||
} | ||
|
||
// NewContainer creates a method container. | ||
func NewContainer() *Container { | ||
return &Container{ | ||
instances: make(map[reflect.Type]interface{}), | ||
} | ||
} | ||
|
||
// Put puts an instance in this container. The instance must have one or more methods. | ||
func (c *Container) Put(instance interface{}) { | ||
typ := reflect.TypeOf(instance) | ||
if typ.NumMethod() <= 0 { | ||
panic(fmt.Errorf("type %s has no method", typ.String())) | ||
} | ||
c.lock.Lock() | ||
defer c.lock.Unlock() | ||
c.instances[typ] = instance | ||
} | ||
|
||
// PutInterface puts an instance in this container. The instance must have one or more methods. | ||
// The iface should be like (*ArbitraryInterface)(nil). | ||
func (c *Container) PutInterface(iface interface{}, instance interface{}) { | ||
typ := c.typeOf(iface) | ||
if typ.Kind() != reflect.Interface { | ||
panic(fmt.Errorf("type %s doesn't an interface", typ.String())) | ||
} | ||
if typ.NumMethod() <= 0 { | ||
panic(fmt.Errorf("type %s has no method", typ.String())) | ||
} | ||
c.lock.Lock() | ||
defer c.lock.Unlock() | ||
c.instances[typ] = instance | ||
} | ||
|
||
// funcOf gets function value. | ||
func (c *Container) funcOf(typ reflect.Type, method string) reflect.Value { | ||
c.lock.RLock() | ||
ins, ok := c.instances[typ] | ||
c.lock.RUnlock() | ||
if !ok { | ||
panic(fmt.Errorf("no instance for type %s", typ)) | ||
} | ||
return reflect.ValueOf(ins).MethodByName(method) | ||
} | ||
|
||
// Get returns a function for specified method. If you want to specify a method from an | ||
// interface, you need to use (*ArbitraryInterface)(nil) as instance. | ||
func (c *Container) Get(instance interface{}, method string) interface{} { | ||
typ, funcTyp := c.typesOf(instance, method) | ||
var lock sync.Mutex | ||
var value *reflect.Value | ||
return reflect.MakeFunc(funcTyp, func(args []reflect.Value) (results []reflect.Value) { | ||
if value == nil { | ||
// Only get func value once. | ||
lock.Lock() | ||
if value == nil { | ||
v := c.funcOf(typ, method) | ||
value = &v | ||
} | ||
// If it paniced, this mutex won't unlock. | ||
// It doesn't matter. | ||
lock.Unlock() | ||
} | ||
return value.Call(args) | ||
}).Interface() | ||
} | ||
|
||
// typesOf returns instance type and func type. | ||
func (c *Container) typesOf(instance interface{}, method string) (insType reflect.Type, funcType reflect.Type) { | ||
if method == "" { | ||
panic(fmt.Errorf("method must not be empty")) | ||
} | ||
insType = c.typeOf(instance) | ||
if insType.NumMethod() <= 0 { | ||
panic(fmt.Errorf("type %s has no method", insType.String())) | ||
} | ||
m, ok := insType.MethodByName(method) | ||
if !ok { | ||
panic(fmt.Errorf("no method named %s in type %s", method, insType.String())) | ||
} | ||
funcType = m.Type | ||
if insType.Kind() != reflect.Interface { | ||
ins := make([]reflect.Type, funcType.NumIn()-1) | ||
for i := 1; i < funcType.NumIn(); i++ { | ||
ins[i-1] = funcType.In(i) | ||
} | ||
outs := make([]reflect.Type, funcType.NumOut()) | ||
for i := 0; i < funcType.NumOut(); i++ { | ||
outs[i] = funcType.Out(i) | ||
} | ||
funcType = reflect.FuncOf(ins, outs, funcType.IsVariadic()) | ||
} | ||
return insType, funcType | ||
} | ||
|
||
// typeOf gets original type of instance. | ||
func (c *Container) typeOf(instance interface{}) reflect.Type { | ||
typ := reflect.TypeOf(instance) | ||
if typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Interface { | ||
// Replace *interface{} with interface{} | ||
typ = typ.Elem() | ||
} | ||
return typ | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
/* | ||
Copyright 2018 Caicloud Authors | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package method | ||
|
||
import ( | ||
"reflect" | ||
"testing" | ||
) | ||
|
||
type TestInterface interface { | ||
Number() int | ||
} | ||
|
||
type TestStruct struct { | ||
a int | ||
} | ||
|
||
func (t *TestStruct) Number() int { | ||
return t.a | ||
} | ||
|
||
type TestStruct2 struct { | ||
a int | ||
} | ||
|
||
func (t *TestStruct2) Number() int { | ||
return t.a * 2 | ||
} | ||
|
||
func TestContainer(t *testing.T) { | ||
var ts TestInterface = &TestStruct2{100} | ||
cases := []struct { | ||
typ interface{} | ||
instance interface{} | ||
method string | ||
result int | ||
}{ | ||
{&TestStruct{}, &TestStruct{100}, "Number", 100}, | ||
{(*TestInterface)(nil), &TestStruct{100}, "Number", 100}, | ||
{(*TestInterface)(nil), TestInterface(&TestStruct{100}), "Number", 100}, | ||
{(*TestInterface)(nil), ts, "Number", 200}, | ||
} | ||
for _, c := range cases { | ||
f := Get(c.typ, c.method) | ||
if defaultContainer.typeOf(c.typ).Kind() == reflect.Interface { | ||
PutInterface(c.typ, c.instance) | ||
} else { | ||
Put(c.instance) | ||
} | ||
result := f.(func() int)() | ||
if result != c.result { | ||
t.Fatalf("Function result should be %d, but got: %d", c.result, result) | ||
} | ||
} | ||
} | ||
|
||
func BenchmarkContainer(b *testing.B) { | ||
c := NewContainer() | ||
f := c.Get(&TestStruct{}, "Number") | ||
c.Put(&TestStruct{100}) | ||
fn := reflect.ValueOf(f) | ||
for i := 0; i < b.N; i++ { | ||
fn.Call([]reflect.Value{}) | ||
} | ||
} | ||
|
||
func BenchmarkDirect(b *testing.B) { | ||
fn := reflect.ValueOf(&TestStruct{100}).MethodByName("Number") | ||
for i := 0; i < b.N; i++ { | ||
fn.Call([]reflect.Value{}) | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
add another struct implement TestInterface,used for test putInterface.