Exemplo n.º 1
0
Arquivo: var.go Projeto: TuneDB/env
func parseFloat(value string) (reflect.Value, error) {
	b, err := strconv.ParseFloat(value, 64)
	if err != nil {
		return reflect.ValueOf(nil), conversionError(value, "float64")
	}
	return reflect.ValueOf(b), nil
}
Exemplo n.º 2
0
// ObjectsAreEqual determines if two objects are considered equal.
//
// This function does no assertion of any kind.
func ObjectsAreEqual(expected, actual interface{}) bool {

	if expected == nil || actual == nil {
		return expected == actual
	}

	if reflect.DeepEqual(expected, actual) {
		return true
	}

	expectedValue := reflect.ValueOf(expected)
	actualValue := reflect.ValueOf(actual)
	if expectedValue == actualValue {
		return true
	}

	// Attempt comparison after type conversion
	if actualValue.Type().ConvertibleTo(expectedValue.Type()) && expectedValue == actualValue.Convert(expectedValue.Type()) {
		return true
	}

	// Last ditch effort
	if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) {
		return true
	}

	return false

}
Exemplo n.º 3
0
func (t *Table) CopyDataLine(dims cube.Dimensions, aggs cube.Aggregates) string {
	ints := make([]interface{}, 0, len(t.aggcols)+len(t.dimcols))

	vDims := reflect.ValueOf(dims)
	vAggs := reflect.ValueOf(aggs)

	i := 0
	visitor := func(fieldValue reflect.Value, fieldDescription reflect.StructField) {
		ints = append(ints, t.dimcols[i].PrintInterface(fieldValue.Interface()))
		i += 1
	}
	VisitDimensions(vDims, visitor)

	j := 0
	visitorAgg := func(fieldValue reflect.Value, fieldDescription reflect.StructField) {
		ints = append(ints, t.aggcols[j].PrintInterface(fieldValue.Elem().Interface()))
		j += 1
	}

	VisitAggregates(vAggs, visitorAgg)
	/*
			for _, col := range t.dimcols {
				ints = append(ints, col.PrintInterface(vDims.Field(col.Index()).Interface()))
			}
		for _, col := range t.aggcols {
			ints = append(ints, col.PrintInterface(vAggs.Field(col.Index()).Elem().Interface()))
		}*/

	fs := t.getCopyDataLineFormatString()
	return fmt.Sprintf(fs, ints...)
}
Exemplo n.º 4
0
func Mod(a, b interface{}) (int64, error) {
	av := reflect.ValueOf(a)
	bv := reflect.ValueOf(b)
	var ai, bi int64

	switch av.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		ai = av.Int()
	default:
		return 0, errors.New("Modulo operator can't be used with non integer value")
	}

	switch bv.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		bi = bv.Int()
	default:
		return 0, errors.New("Modulo operator can't be used with non integer value")
	}

	if bi == 0 {
		return 0, errors.New("The number can't be divided by zero at modulo operation")
	}

	return ai % bi, nil
}
Exemplo n.º 5
0
// Exec executes the statement represented by the InsertBuilder
// It returns the raw database/sql Result and an error if there was one.
// Regarding LastInsertID(): If you insert multiple rows using a single
// INSERT statement, LAST_INSERT_ID() returns the value generated for
// the first inserted row only. The reason for this is to make it possible to
// reproduce easily the same INSERT statement against some other server.
func (b *InsertBuilder) Exec() (sql.Result, error) {
	sql, args := b.ToSql()

	fullSql, err := Preprocess(sql, args)
	if err != nil {
		return nil, b.EventErrKv("dbr.insert.exec.interpolate", err, kvs{"sql": sql, "args": fmt.Sprint(args)})
	}

	// Start the timer:
	startTime := time.Now()
	defer func() { b.TimingKv("dbr.insert", time.Since(startTime).Nanoseconds(), kvs{"sql": fullSql}) }()

	result, err := b.runner.Exec(fullSql)
	if err != nil {
		return result, b.EventErrKv("dbr.insert.exec.exec", err, kvs{"sql": fullSql})
	}

	// If the structure has an "Id" field which is an int64, set it from the LastInsertId(). Otherwise, don't bother.
	if len(b.Recs) == 1 {
		rec := b.Recs[0]
		val := reflect.Indirect(reflect.ValueOf(rec))
		if val.Kind() == reflect.Struct && val.CanSet() {
			// @todo important: make Id configurable to match all magento internal ID columns
			if idField := val.FieldByName("Id"); idField.IsValid() && idField.Kind() == reflect.Int64 {
				if lastID, err := result.LastInsertId(); err == nil {
					idField.Set(reflect.ValueOf(lastID))
				} else {
					b.EventErrKv("dbr.insert.exec.last_inserted_id", err, kvs{"sql": fullSql})
				}
			}
		}
	}

	return result, nil
}
Exemplo n.º 6
0
// Union outputs a collection that holds unique values of in and values collections
func Union(in Collection, values Collection, out Pointer) error {

	if !IsCollection(in) {
		return NotACollection("Value %v is not a collection", in)
	}
	if !IsCollection(values) {
		return NotACollection("Value %v is not a collection", values)
	}
	if !IsPointer(out) {
		return NotPointer("Value %v is not a pointer", out)
	}
	inVal := reflect.ValueOf(in)
	valuesVal := reflect.ValueOf(values)
	outVal := reflect.ValueOf(out)
	if a, b := inVal.Type(), valuesVal.Type(); a != b {
		return NotAssignable("Collection of type '%v' doesn't match type  ", a, b)
	}
	if a, c := inVal.Type(), outVal.Elem().Type(); !a.AssignableTo(c) {
		return NotAssignable("Collection of type '%v' is not assignable to output of type '%v'", a, c)
	}
	for i := 0; i < valuesVal.Len(); i++ {
		inVal = reflect.Append(inVal, valuesVal.Index(i))
	}
	if err := Unique(inVal.Interface(), out); err != nil {
		return err
	}
	return nil
}
Exemplo n.º 7
0
func ReturnWhenSet(a, k interface{}) interface{} {
	av, isNil := indirect(reflect.ValueOf(a))
	if isNil {
		return ""
	}

	var avv reflect.Value
	switch av.Kind() {
	case reflect.Array, reflect.Slice:
		index, ok := k.(int)
		if ok && av.Len() > index {
			avv = av.Index(index)
		}
	case reflect.Map:
		kv := reflect.ValueOf(k)
		if kv.Type().AssignableTo(av.Type().Key()) {
			avv = av.MapIndex(kv)
		}
	}

	if avv.IsValid() {
		switch avv.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			return avv.Int()
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			return avv.Uint()
		case reflect.Float32, reflect.Float64:
			return avv.Float()
		case reflect.String:
			return avv.String()
		}
	}

	return ""
}
Exemplo n.º 8
0
func (mw *middlewareHandler) invoke(ctx reflect.Value, rw ResponseWriter, req *Request, next NextMiddlewareFunc) {
	if mw.Generic {
		mw.GenericMiddleware(rw, req, next)
	} else {
		mw.DynamicMiddleware.Call([]reflect.Value{ctx, reflect.ValueOf(rw), reflect.ValueOf(req), reflect.ValueOf(next)})
	}
}
Exemplo n.º 9
0
// Beat the supplied handler into a uniform signature. panics if incompatible
// (may only happen when the wrapped fun is called)
func fixHandlerSignature(f interface{}) parametrizedHandler {
	// classic net/http.Hander implementors can easily be converted
	if httph, ok := f.(http.Handler); ok {
		return func(ctx *Context, args ...string) error {
			httph.ServeHTTP(ctx.Response, ctx.Request)
			return nil
		}
	}
	fv := reflect.ValueOf(f)
	var callf valuefun = callableValue(fv)
	if !requiresContext(fv.Type()) {
		callf = disregardFirstArg(callf)
	}
	// now callf definitely accepts a *Context as its first arg
	if !lastRetIsError(fv) {
		callf = addNilErrorReturn(callf)
	}
	// now callf definitely returns an error as its last value
	if firstRetIsNonError(fv) {
		callf = writeFirstRetToFirstArg(callf)
	}
	// now callf definitely does not return its data: just an error
	// wrap callf in a function with pretty signature
	return func(ctx *Context, args ...string) error {
		argvs := make([]reflect.Value, len(args)+1)
		argvs[0] = reflect.ValueOf(ctx)
		for i, arg := range args {
			argvs[i+1] = reflect.ValueOf(arg)
		}
		rets := callf(argvs)
		return value2error(rets[0])
	}
}
Exemplo n.º 10
0
func TestReflection(t *testing.T) {
	o := js.Global.Call("eval", "({ answer: 42 })")
	if reflect.ValueOf(o).Interface().(*js.Object) != o {
		t.Fail()
	}

	type S struct {
		Field *js.Object
	}
	s := S{o}

	v := reflect.ValueOf(&s).Elem()
	if v.Field(0).Interface().(*js.Object).Get("answer").Int() != 42 {
		t.Fail()
	}
	if v.Field(0).MethodByName("Get").Call([]reflect.Value{reflect.ValueOf("answer")})[0].Interface().(*js.Object).Int() != 42 {
		t.Fail()
	}
	v.Field(0).Set(reflect.ValueOf(js.Global.Call("eval", "({ answer: 100 })")))
	if s.Field.Get("answer").Int() != 100 {
		t.Fail()
	}

	if fmt.Sprintf("%+v", s) != "{Field:[object Object]}" {
		t.Fail()
	}
}
Exemplo n.º 11
0
func (context *Context) valueOf(valuer func(interface{}, *qor.Context) interface{}, value interface{}, meta *Meta) interface{} {
	if valuer != nil {
		reflectValue := reflect.ValueOf(value)
		if reflectValue.Kind() != reflect.Ptr {
			reflectPtr := reflect.New(reflectValue.Type())
			reflectPtr.Elem().Set(reflectValue)
			value = reflectPtr.Interface()
		}

		result := valuer(value, context.Context)

		if reflectValue := reflect.ValueOf(result); reflectValue.IsValid() {
			if reflectValue.Kind() == reflect.Ptr {
				if reflectValue.IsNil() || !reflectValue.Elem().IsValid() {
					return nil
				}

				result = reflectValue.Elem().Interface()
			}

			if meta.Type == "number" || meta.Type == "float" {
				if context.isNewRecord(value) && equal(reflect.Zero(reflect.TypeOf(result)).Interface(), result) {
					return nil
				}
			}
			return result
		} else {
			return nil
		}
	}

	utils.ExitWithMsg(fmt.Sprintf("No valuer found for meta %v of resource %v", meta.Name, meta.baseResource.Name))
	return nil
}
Exemplo n.º 12
0
// lt evaluates the comparison a < b.
func lt(arg1, arg2 interface{}) (bool, error) {
	v1 := reflect.ValueOf(arg1)
	k1, err := basicKind(v1)
	if err != nil {
		return false, err
	}
	v2 := reflect.ValueOf(arg2)
	k2, err := basicKind(v2)
	if err != nil {
		return false, err
	}
	if k1 != k2 {
		return false, errBadComparison
	}
	truth := false
	switch k1 {
	case boolKind, complexKind:
		return false, errBadComparisonType
	case floatKind:
		truth = v1.Float() < v2.Float()
	case intKind:
		truth = v1.Int() < v2.Int()
	case stringKind:
		truth = v1.String() < v2.String()
	case uintKind:
		truth = v1.Uint() < v2.Uint()
	default:
		panic("invalid kind")
	}
	return truth, nil
}
Exemplo n.º 13
0
func RPC2XML(value interface{}) (string, error) {
	out := "<value>"
	switch reflect.ValueOf(value).Kind() {
	case reflect.Int:
		out += fmt.Sprintf("<int>%d</int>", value.(int))
	case reflect.Float64:
		out += fmt.Sprintf("<double>%f</double>", value.(float64))
	case reflect.String:
		out += String2XML(value.(string))
	case reflect.Bool:
		out += Bool2XML(value.(bool))
	case reflect.Struct:
		if reflect.TypeOf(value).String() != "time.Time" {
			out += Struct2XML(value)
		} else {
			out += Time2XML(value.(time.Time))
		}
	case reflect.Slice, reflect.Array:
		// FIXME: is it the best way to recognize '[]byte'?
		if reflect.TypeOf(value).String() != "[]uint8" {
			out += Array2XML(value)
		} else {
			out += Base642XML(value.([]byte))
		}
	case reflect.Ptr:
		if reflect.ValueOf(value).IsNil() {
			out += "<nil/>"
		}
	}
	out += "</value>"
	return out, nil
}
Exemplo n.º 14
0
Arquivo: var.go Projeto: TuneDB/env
// NewVarWithFunc returns a new Var. get returns the value for the given key
func NewVarWithFunc(field reflect.StructField, get func(string) string) (*Var, error) {
	newVar := &Var{}
	newVar.Parse(field)

	value, err := convert(newVar.Type, get(newVar.Key), newVar.Decode)
	if err != nil {
		return newVar, err
	}
	newVar.SetValue(value)

	if value == reflect.ValueOf(nil) {
		if newVar.Required {
			return newVar, fmt.Errorf("%s required", newVar.Key)
		}

		// Check if we have a default value to set, otherwise set the type's zero value
		if newVar.Default != reflect.ValueOf(nil) {
			newVar.SetValue(newVar.Default)
		} else {
			newVar.SetValue(reflect.Zero(newVar.Type))
		}
	}

	if len(newVar.Options) > 0 {
		if !newVar.optionsContains(newVar.Value) {
			return newVar, fmt.Errorf(`%v="%v" not in allowed options: %v`, newVar.Key, newVar.Value, newVar.Options)
		}
	}

	return newVar, nil
}
Exemplo n.º 15
0
func main() {
	var x float64 = 6.54
	v := reflect.ValueOf(x)
	fmt.Println("type:", reflect.TypeOf(x))
	fmt.Println("value:", reflect.ValueOf(x))
	fmt.Println("kind is float64:", v.Kind() == reflect.String)
}
Exemplo n.º 16
0
func handlerName(h HandlerFunc) string {
	t := reflect.ValueOf(h).Type()
	if t.Kind() == reflect.Func {
		return runtime.FuncForPC(reflect.ValueOf(h).Pointer()).Name()
	}
	return t.String()
}
Exemplo n.º 17
0
// Unique filters remove duplicate values from an array
func Unique(in Collection, out Pointer) error {
	if !IsCollection(in) {
		return NotACollection("Value '%v' is not a collection", in)
	}
	if !IsPointer(out) {
		return NotPointer("Value '%v' is not a pointer", out)
	}
	inValue := reflect.ValueOf(in)
	inType := inValue.Type()
	outValue := reflect.ValueOf(out)
	outType := outValue.Type()
	if !inType.AssignableTo(outType.Elem()) {
		return NotAssignable("Value in of type '%v' can't be assigned to out  of type '%v' ", inType, outType.Elem())
	}
	newCollection := reflect.MakeSlice(inType, 0, 0)
	inLen := inValue.Len()
	for i := 0; i < inLen; i++ {
		if index, err := IndexOf(newCollection.Interface(), inValue.Index(i).Interface(), 0); err != nil {
			return err
		} else if index == -1 {
			newCollection = reflect.Append(newCollection, inValue.Index(i))
		}

	}
	outValue.Elem().Set(newCollection)
	return nil
}
Exemplo n.º 18
0
// Магия, через reflect и таги "logfield"/"logresize" выставить все поля структуры LogData в
// соответствующие значения из json-лога
func parseJSONLines(lines [][]byte, res interface{}) {
	resType := reflect.TypeOf(res).Elem()
	resValue := reflect.ValueOf(res).Elem()

	for i := 0; i < resType.NumField(); i++ {
		field := resValue.Field(i)
		fieldType := resType.Field(i)
		fieldTag := fieldType.Tag
		if fieldTag.Get("logfield") != "" || fieldTag.Get("logresize") != "" {
			field.Set(reflect.MakeSlice(fieldType.Type, len(lines), len(lines)))
		}
	}

	resValue.FieldByName("Size").Set(reflect.ValueOf(len(lines)))

	for lineno, l := range lines {
		var ll map[string]string
		err := json.Unmarshal(l, &ll)
		if err == nil {
			for i := 0; i < resType.NumField(); i++ {
				field := resValue.Field(i)
				fieldTag := resType.Field(i).Tag.Get("logfield")

				if fieldTag != "" {
					valueFromJSON := reflect.ValueOf(ll[fieldTag])
					field.Index(lineno).Set(valueFromJSON)
				}
			}
		} else {
			fmt.Printf("err: %v; %s\n", err, l)
		}
	}
}
Exemplo n.º 19
0
// WaitForNetworkConnectivity uses a NetworkConnectivityChecker to
// periodically check for network connectivity. It returns true if
// no NetworkConnectivityChecker is provided (waiting is disabled)
// or when NetworkConnectivityChecker.HasNetworkConnectivity()
// indicates connectivity. It waits and polls the checker once a second.
// If any stop is broadcast, false is returned immediately.
func WaitForNetworkConnectivity(
	connectivityChecker NetworkConnectivityChecker, stopBroadcasts ...<-chan struct{}) bool {
	if connectivityChecker == nil || 1 == connectivityChecker.HasNetworkConnectivity() {
		return true
	}
	NoticeInfo("waiting for network connectivity")
	ticker := time.NewTicker(1 * time.Second)
	for {
		if 1 == connectivityChecker.HasNetworkConnectivity() {
			return true
		}

		selectCases := make([]reflect.SelectCase, 1+len(stopBroadcasts))
		selectCases[0] = reflect.SelectCase{
			Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ticker.C)}
		for i, stopBroadcast := range stopBroadcasts {
			selectCases[i+1] = reflect.SelectCase{
				Dir: reflect.SelectRecv, Chan: reflect.ValueOf(stopBroadcast)}
		}

		chosen, _, ok := reflect.Select(selectCases)
		if chosen == 0 && ok {
			// Ticker case, so check again
		} else {
			// Stop case
			return false
		}
	}
}
Exemplo n.º 20
0
func (s *S) TestUnmarshal(c *C) {
	for i, item := range unmarshalTests {
		t := reflect.ValueOf(item.value).Type()
		var value interface{}
		switch t.Kind() {
		case reflect.Map:
			value = reflect.MakeMap(t).Interface()
		case reflect.String:
			t := reflect.ValueOf(item.value).Type()
			v := reflect.New(t)
			value = v.Interface()
		default:
			pt := reflect.ValueOf(item.value).Type()
			pv := reflect.New(pt.Elem())
			value = pv.Interface()
		}
		err := goyaml.Unmarshal([]byte(item.data), value)
		c.Assert(err, IsNil, Commentf("Item #%d", i))
		if t.Kind() == reflect.String {
			c.Assert(*value.(*string), Equals, item.value, Commentf("Item #%d", i))
		} else {
			c.Assert(value, DeepEquals, item.value, Commentf("Item #%d", i))
		}
	}
}
Exemplo n.º 21
0
func refPage(page interface{}, ref, methodName string) template.HTML {
	value := reflect.ValueOf(page)

	method := value.MethodByName(methodName)

	if method.IsValid() && method.Type().NumIn() == 1 && method.Type().NumOut() == 2 {
		result := method.Call([]reflect.Value{reflect.ValueOf(ref)})

		url, err := result[0], result[1]

		if !err.IsNil() {
			jww.ERROR.Printf("%s", err.Interface())
			return template.HTML(fmt.Sprintf("%s", err.Interface()))
		}

		if url.String() == "" {
			jww.ERROR.Printf("ref %s could not be found\n", ref)
			return template.HTML(ref)
		}

		return template.HTML(url.String())
	}

	jww.ERROR.Printf("Can only create references from Page and Node objects.")
	return template.HTML(ref)
}
Exemplo n.º 22
0
func setValue(dstVal reflect.Value, src interface{}) {
	if dstVal.Kind() == reflect.Ptr {
		dstVal = reflect.Indirect(dstVal)
	}
	srcVal := reflect.ValueOf(src)

	if !srcVal.IsValid() { // src is literal nil
		if dstVal.CanAddr() {
			// Convert to pointer so that pointer's value can be nil'ed
			//                     dstVal = dstVal.Addr()
		}
		dstVal.Set(reflect.Zero(dstVal.Type()))

	} else if srcVal.Kind() == reflect.Ptr {
		if srcVal.IsNil() {
			srcVal = reflect.Zero(dstVal.Type())
		} else {
			srcVal = reflect.ValueOf(src).Elem()
		}
		dstVal.Set(srcVal)
	} else {
		dstVal.Set(srcVal)
	}

}
Exemplo n.º 23
0
// After is exposed to templates, to iterate over all the items after N in a
// rangeable list. It's meant to accompany First
func After(index interface{}, seq interface{}) (interface{}, error) {

	if index == nil || seq == nil {
		return nil, errors.New("both limit and seq must be provided")
	}

	indexv, err := cast.ToIntE(index)

	if err != nil {
		return nil, err
	}

	if indexv < 1 {
		return nil, errors.New("can't return negative/empty count of items from sequence")
	}

	seqv := reflect.ValueOf(seq)
	seqv, isNil := indirect(seqv)
	if isNil {
		return nil, errors.New("can't iterate over a nil value")
	}

	switch seqv.Kind() {
	case reflect.Array, reflect.Slice, reflect.String:
		// okay
	default:
		return nil, errors.New("can't iterate over " + reflect.ValueOf(seq).Type().String())
	}
	if indexv >= seqv.Len() {
		return nil, errors.New("no items left")
	}
	return seqv.Slice(indexv, seqv.Len()).Interface(), nil
}
Exemplo n.º 24
0
// Performs a request/response call for when the message is not NoWait and is
// specified as Synchronous.
func (me *Channel) call(req message, res ...message) error {
	if err := me.send(me, req); err != nil {
		return err
	}

	if req.wait() {
		select {
		case e := <-me.errors:
			return e

		case msg := <-me.rpc:
			if msg != nil {
				for _, try := range res {
					if reflect.TypeOf(msg) == reflect.TypeOf(try) {
						// *res = *msg
						vres := reflect.ValueOf(try).Elem()
						vmsg := reflect.ValueOf(msg).Elem()
						vres.Set(vmsg)
						return nil
					}
				}
				return ErrCommandInvalid
			} else {
				// RPC channel has been closed without an error, likely due to a hard
				// error on the Connection.  This indicates we have already been
				// shutdown and if were waiting, will have returned from the errors chan.
				return ErrClosed
			}
		}
	}

	return nil
}
Exemplo n.º 25
0
func (t *typeValidator) Validate(data interface{}) *Result {
	result := new(Result)
	result.Inc()
	if data == nil || reflect.DeepEqual(reflect.Zero(reflect.TypeOf(data)), reflect.ValueOf(data)) {
		if len(t.Type) > 0 && !t.Type.Contains("null") { // TODO: if a property is not required it also passes this
			return sErr(errors.InvalidType(t.Path, t.In, strings.Join(t.Type, ","), "null"))
		}
		return result
	}

	// check if the type matches, should be used in every validator chain as first item
	val := reflect.Indirect(reflect.ValueOf(data))

	schType, format := t.schemaInfoForType(data)
	isLowerInt := t.Format == "int64" && format == "int32"
	isLowerFloat := t.Format == "float64" && format == "float32"

	if val.Kind() != reflect.String && t.Format != "" && !(format == t.Format || isLowerInt || isLowerFloat) {
		return sErr(errors.InvalidType(t.Path, t.In, t.Format, format))
	}
	if t.Format != "" && val.Kind() == reflect.String {
		return result
	}

	isFloatInt := schType == "number" && swag.IsFloat64AJSONInteger(val.Float()) && t.Type.Contains("integer")
	isIntFloat := schType == "integer" && t.Type.Contains("number")
	if !(t.Type.Contains(schType) || isFloatInt || isIntFloat) {
		return sErr(errors.InvalidType(t.Path, t.In, strings.Join(t.Type, ","), schType))
	}
	return result
}
Exemplo n.º 26
0
func (me *Connection) call(req message, res ...message) error {
	// Special case for when the protocol header frame is sent insted of a
	// request method
	if req != nil {
		if err := me.send(&methodFrame{ChannelId: 0, Method: req}); err != nil {
			return err
		}
	}

	select {
	case err := <-me.errors:
		if err == nil {
			return ErrClosed
		}
		return err

	case msg := <-me.rpc:
		// Try to match one of the result types
		for _, try := range res {
			if reflect.TypeOf(msg) == reflect.TypeOf(try) {
				// *res = *msg
				vres := reflect.ValueOf(try).Elem()
				vmsg := reflect.ValueOf(msg).Elem()
				vres.Set(vmsg)
				return nil
			}
		}
		return ErrCommandInvalid
	}

	panic("unreachable")
}
Exemplo n.º 27
0
func (rw *ResponderWorker) Call(serviceMethod string, args interface{}, reply interface{}) error {
	methodName := strings.TrimLeft(serviceMethod, "Responder.")
	switch args.(type) {
	case CallDescriptor:
		cd := args.(CallDescriptor)
		switch reply.(type) {
		case *CallCost:
			rep := reply.(*CallCost)
			method := reflect.ValueOf(&cd).MethodByName(methodName)
			ret := method.Call([]reflect.Value{})
			*rep = *(ret[0].Interface().(*CallCost))
		case *float64:
			rep := reply.(*float64)
			method := reflect.ValueOf(&cd).MethodByName(methodName)
			ret := method.Call([]reflect.Value{})
			*rep = *(ret[0].Interface().(*float64))
		}
	case string:
		switch methodName {
		case "Status":
			*(reply.(*string)) = "Local!"
		case "Shutdown":
			*(reply.(*string)) = "Done!"
		}

	}
	return nil
}
Exemplo n.º 28
0
func BenchmarkHandlerCall(b *testing.B) {

	fn := func(params *jsonrpc2.EmptyParams) (interface{}, error) {

		return nil, nil
	}

	handler := handler{
		method: reflect.ValueOf(fn),
		params: reflect.New(reflect.ValueOf(fn).Type().In(0).Elem()).Interface().(jsonrpc2.Params),
	}
	data, _ := json.Marshal(&jsonrpc2.EmptyParams{})

	params, err := handler.DecodeParams(data)

	if err != nil {

		b.Fatal(err.Error())
	}

	b.ResetTimer()
	b.ReportAllocs()

	for i := 0; i < b.N; i++ {

		handler.Call(params)
	}
}
Exemplo n.º 29
0
func TestNormalizationFuncGlobalExistence(t *testing.T) {
	// This test can be safely deleted when we will not support multiple flag formats
	root := NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, os.Stdout, os.Stderr)

	if root.Parent() != nil {
		t.Fatal("We expect the root command to be returned")
	}
	if root.GlobalNormalizationFunc() == nil {
		t.Fatal("We expect that root command has a global normalization function")
	}

	if reflect.ValueOf(root.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(root.Flags().GetNormalizeFunc()).Pointer() {
		t.Fatal("root command seems to have a wrong normalization function")
	}

	sub := root
	for sub.HasSubCommands() {
		sub = sub.Commands()[0]
	}

	// In case of failure of this test check this PR: spf13/cobra#110
	if reflect.ValueOf(sub.Flags().GetNormalizeFunc()).Pointer() != reflect.ValueOf(root.Flags().GetNormalizeFunc()).Pointer() {
		t.Fatal("child and root commands should have the same normalization functions")
	}
}
Exemplo n.º 30
0
Arquivo: var.go Projeto: TuneDB/env
// Convert a string into the specified type.
// Return the type's zero value if we receive an empty string
// Use the decode strategy defined
func convert(t reflect.Type, value string, decode string) (reflect.Value, error) {
	if value == "" {
		return reflect.ValueOf(nil), nil
	}

	switch decode {
	// if no decode defined, try with type and then kind
	// if any type is defined then it will be used else fallback to kind
	case "":
		val, err := convertWithType(t, value)

		if err != nil {
			val, err = convertWithKind(t, value)
		}

		return val, err
	case "kind":
		return convertWithKind(t, value)
	case "type":
		return convertWithType(t, value)
	case "yaml":
		return convertWithYaml(t, value)
	default:
		return reflect.ValueOf(nil), conversionError(decode, `unsupported decode`)
	}
}