Home | History | Annotate | Download | only in function
      1 // Copyright 2017, 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.md file.
      4 
      5 // Package function identifies function types.
      6 package function
      7 
      8 import "reflect"
      9 
     10 type funcType int
     11 
     12 const (
     13 	_ funcType = iota
     14 
     15 	ttbFunc // func(T, T) bool
     16 	tibFunc // func(T, I) bool
     17 	trFunc  // func(T) R
     18 
     19 	Equal           = ttbFunc // func(T, T) bool
     20 	EqualAssignable = tibFunc // func(T, I) bool; encapsulates func(T, T) bool
     21 	Transformer     = trFunc  // func(T) R
     22 	ValueFilter     = ttbFunc // func(T, T) bool
     23 	Less            = ttbFunc // func(T, T) bool
     24 )
     25 
     26 var boolType = reflect.TypeOf(true)
     27 
     28 // IsType reports whether the reflect.Type is of the specified function type.
     29 func IsType(t reflect.Type, ft funcType) bool {
     30 	if t == nil || t.Kind() != reflect.Func || t.IsVariadic() {
     31 		return false
     32 	}
     33 	ni, no := t.NumIn(), t.NumOut()
     34 	switch ft {
     35 	case ttbFunc: // func(T, T) bool
     36 		if ni == 2 && no == 1 && t.In(0) == t.In(1) && t.Out(0) == boolType {
     37 			return true
     38 		}
     39 	case tibFunc: // func(T, I) bool
     40 		if ni == 2 && no == 1 && t.In(0).AssignableTo(t.In(1)) && t.Out(0) == boolType {
     41 			return true
     42 		}
     43 	case trFunc: // func(T) R
     44 		if ni == 1 && no == 1 {
     45 			return true
     46 		}
     47 	}
     48 	return false
     49 }
     50