func bindFile(params *Params, name string, typ reflect.Type) reflect.Value { reader := getMultipartFile(params, name) if reader == nil { return reflect.Zero(typ) } // If it's already stored in a temp file, just return that. if osFile, ok := reader.(*os.File); ok { return reflect.ValueOf(osFile) } // Otherwise, have to store it. tmpFile, err := ioutil.TempFile("", "revel-upload") if err != nil { WARN.Println("Failed to create a temp file to store upload:", err) return reflect.Zero(typ) } // Register it to be deleted after the request is done. params.tmpFiles = append(params.tmpFiles, tmpFile) _, err = io.Copy(tmpFile, reader) if err != nil { WARN.Println("Failed to copy upload to temp file:", err) return reflect.Zero(typ) } _, err = tmpFile.Seek(0, 0) if err != nil { WARN.Println("Failed to seek to beginning of temp file:", err) return reflect.Zero(typ) } return reflect.ValueOf(tmpFile) }
func (association *Association) getPrimaryKeys(values ...interface{}) []interface{} { primaryKeys := []interface{}{} scope := association.Scope for _, value := range values { reflectValue := reflect.ValueOf(value) if reflectValue.Kind() == reflect.Ptr { reflectValue = reflectValue.Elem() } if reflectValue.Kind() == reflect.Slice { for i := 0; i < reflectValue.Len(); i++ { newScope := scope.New(reflectValue.Index(i).Interface()) primaryKey := newScope.PrimaryKeyValue() if !reflect.DeepEqual(reflect.ValueOf(primaryKey), reflect.Zero(reflect.ValueOf(primaryKey).Type())) { primaryKeys = append(primaryKeys, primaryKey) } } } else if reflectValue.Kind() == reflect.Struct { newScope := scope.New(value) primaryKey := newScope.PrimaryKeyValue() if !reflect.DeepEqual(reflect.ValueOf(primaryKey), reflect.Zero(reflect.ValueOf(primaryKey).Type())) { primaryKeys = append(primaryKeys, primaryKey) } } } return primaryKeys }
func zero(head P, mid string, typ reflect.Type) (value reflect.Value, err error) { switch typ.Kind() { case reflect.Ptr: value = reflect.New(typ.Elem()) case reflect.Map: value = reflect.MakeMap(typ) case reflect.Slice: value = reflect.MakeSlice(typ, 0, 0) case reflect.Chan: value = reflect.MakeChan(typ, 1) case reflect.Func, reflect.Interface, reflect.UnsafePointer: value = reflect.Zero(typ) case reflect.Invalid: err = fmt.Errorf("unable to create '%s' at '%s'", typ, append(head, mid)) default: value = reflect.Zero(typ) } return }
// getPtrValues calls GetValue for each variable which has a proper (pointer) destination func (cur *Cursor) getPtrValues() error { debug("getPtrValues %v %v", cur.bindVarsArr, cur.bindVarsMap) for _, v := range cur.bindVarsArr { if v.destination.IsValid() && !v.isArray { val, err := v.GetValue(0) debug("%s setting %v to %v %v", v, v.destination, val, err) if err != nil { return fmt.Errorf("error getting value of %s: %v", v, err) } if val == nil { v.destination.Elem().Set(reflect.Zero(v.destination.Elem().Type())) } else { v.destination.Elem().Set(reflect.ValueOf(val)) } } } for k, v := range cur.bindVarsMap { if v.destination.IsValid() && !v.isArray { val, err := v.GetValue(0) debug("%s setting %v to %v %v", v, v.destination, val, err) if err != nil { return fmt.Errorf("error getting value of %s(%s): %v", k, v, err) } if val == nil { v.destination.Elem().Set(reflect.Zero(v.destination.Elem().Type())) } else { v.destination.Elem().Set(reflect.ValueOf(val)) } } } return nil }
func (d *mapAsMapDecoder) decode(dv, sv reflect.Value) { dt := dv.Type() dv.Set(reflect.MakeMap(reflect.MapOf(dt.Key(), dt.Elem()))) var mapKey reflect.Value var mapElem reflect.Value keyType := dv.Type().Key() elemType := dv.Type().Elem() for _, sElemKey := range sv.MapKeys() { var dElemKey reflect.Value var dElemVal reflect.Value if !mapKey.IsValid() { mapKey = reflect.New(keyType).Elem() } else { mapKey.Set(reflect.Zero(keyType)) } dElemKey = mapKey if !mapElem.IsValid() { mapElem = reflect.New(elemType).Elem() } else { mapElem.Set(reflect.Zero(elemType)) } dElemVal = mapElem d.keyDec(dElemKey, sElemKey) d.elemDec(dElemVal, sv.MapIndex(sElemKey)) dv.SetMapIndex(dElemKey, dElemVal) } }
func (ms *GobMarshaller) Prepare(name string, fn interface{}) (err error) { var ( fT reflect.Type ) // Gob needs to register type before encode/decode if fT = reflect.TypeOf(fn); fT.Kind() != reflect.Func { err = fmt.Errorf("fn is not a function but %v", fn) return } reg := func(v reflect.Value) (err error) { if !v.CanInterface() { err = fmt.Errorf("Can't convert to value in input of %v for name:%v", fn, name) return } gob.Register(v.Interface()) return } for i := 0; i < fT.NumIn(); i++ { // create a zero value of the type of parameters if err = reg(reflect.Zero(fT.In(i))); err != nil { return } } for i := 0; i < fT.NumOut(); i++ { if err = reg(reflect.Zero(fT.Out(i))); err != nil { return } } return }
func dispatch(f interface{}, args ...interface{}) { fv := reflect.ValueOf(f) typ := fv.Type() numReq := typ.NumIn() numVals := numReq if typ.IsVariadic() { numReq-- // variadic can be [] numVals-- if len(args) > numReq { numVals = len(args) } } fargs := make([]reflect.Value, numVals) for i := 0; i < numVals; i++ { if i < len(args) { fargs[i] = reflect.ValueOf(args[i]) } else if i >= numReq { // must be a variadic function fargs[i] = reflect.Zero(typ.In(numReq).Elem()) } else { fargs[i] = reflect.Zero(typ.In(i)) } } fv.Call(fargs) }
// subtractStruct traverses a struct value and subtract each field func subtractStruct(out, in1, in2 reflect.Value, ids map[int]bool) bool { if in1.NumField() != in2.NumField() { log.Fatalf("Tried to subtract two different struct types: %v vs %v", reflect.TypeOf(in1), reflect.TypeOf(in2)) } changed := false for i := 0; i < in1.NumField()-1; i++ { // pointer to field i fieldPtrV1, fieldPtrV2 := in1.Field(i), in2.Field(i) if fieldPtrV1.IsNil() && fieldPtrV2.IsNil() { continue } // pointer to the change diffV := reflect.New(fieldPtrV1.Type().Elem()) delta, isID := false, false if fieldPtrV1.IsNil() { // compare field value with zero value delta, isID = subtractValue(diffV.Elem(), reflect.Zero(fieldPtrV2.Elem().Type()), fieldPtrV2.Elem(), in2.String(), ids[i]) } else if fieldPtrV2.IsNil() { // compare field value with zero value delta, isID = subtractValue(diffV.Elem(), fieldPtrV1.Elem(), reflect.Zero(fieldPtrV1.Elem().Type()), in1.String(), ids[i]) } else { delta, isID = subtractValue(diffV.Elem(), fieldPtrV1.Elem(), fieldPtrV2.Elem(), in1.String(), ids[i]) } if delta || isID { // only save the field in proto if there is a change or value serves as identifier out.Field(i).Set(diffV) } if delta { changed = true } } return changed }
// Validates a struct, returning an error, and a list of field names if any fields tagged as validate:"required" are equal to zero based value. func Required(i interface{}) (error, []string) { var err error t := reflect.TypeOf(i) err = errors.New("Error: " + t.Name() + " has required fields") infractions := []string{} ivalue := reflect.ValueOf(i) for index := 0; index < t.NumField(); index++ { field := t.Field(index) name := field.Name isValidate := field.Tag.Get(VALIDATE) // TODO will want to check what type of validation is happening. For now, only required is respected if isValidate != "" { switch ivalue.FieldByName(name).Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if ivalue.FieldByName(name).Int() == reflect.Zero(field.Type).Int() { infractions = append(infractions, name) } case reflect.String: if ivalue.FieldByName(name).String() == reflect.Zero(field.Type).String() { infractions = append(infractions, name) } } } } if len(infractions) == 0 { err = nil } return err, infractions }
func (c *Call) call(args []interface{}) (rets []interface{}, action func()) { c.numCalls++ // Actions if c.doFunc.IsValid() { doArgs := make([]reflect.Value, len(args)) ft := c.doFunc.Type() for i := 0; i < ft.NumIn(); i++ { if args[i] != nil { doArgs[i] = reflect.ValueOf(args[i]) } else { // Use the zero value for the arg. doArgs[i] = reflect.Zero(ft.In(i)) } } action = func() { c.doFunc.Call(doArgs) } } for n, v := range c.setArgs { reflect.ValueOf(args[n]).Elem().Set(v) } rets = c.rets if rets == nil { // Synthesize the zero value for each of the return args' types. mt := c.methodType() rets = make([]interface{}, mt.NumOut()) for i := 0; i < mt.NumOut(); i++ { rets[i] = reflect.Zero(mt.Out(i)).Interface() } } return }
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) } }
func (d *Decoder) decodeValue(rv reflect.Value, fn decFn) { d.d.initReadNext() if d.d.tryDecodeAsNil() { // If value in stream is nil, set the dereferenced value to its "zero" value (if settable) if rv.Kind() == reflect.Ptr { if !rv.IsNil() { rv.Set(reflect.Zero(rv.Type())) } return } // for rv.Kind() == reflect.Ptr { // rv = rv.Elem() // } if rv.IsValid() { // rv.CanSet() // always settable, except it's invalid rv.Set(reflect.Zero(rv.Type())) } return } // If stream is not containing a nil value, then we can deref to the base // non-pointer value, and decode into that. for rv.Kind() == reflect.Ptr { if rv.IsNil() { rv.Set(reflect.New(rv.Type().Elem())) } rv = rv.Elem() } if fn.i == nil { fn = d.getDecFn(rv.Type()) } fn.f(fn.i, rv) return }
func FileConvert(p *Params, n string, typ reflect.Type) reflect.Value { file := getMultipartFile(p, n) if file == nil { return reflect.Zero(typ) } if osFile, ok := file.(*os.File); ok { return reflect.ValueOf(osFile) } //store temp file osFile, err := ioutil.TempFile("", "peony-upload-file") if err != nil { WARN.Println("create temp file error,", err) return reflect.Zero(typ) } p.tmpFiles = append(p.tmpFiles, osFile) _, err = io.Copy(osFile, file) if err != nil { WARN.Println("save data to temp file error,", err) return reflect.Zero(typ) } _, err = osFile.Seek(0, 0) if err != nil { WARN.Println("seek to begin of temp file error,", err) return reflect.Zero(typ) } return reflect.ValueOf(osFile) }
func reflectPtrTo() { tInt := reflect.TypeOf(3) tPtrInt := reflect.PtrTo(tInt) print(reflect.Zero(tPtrInt)) // @types *int tPtrPtrInt := reflect.PtrTo(tPtrInt) print(reflect.Zero(tPtrPtrInt)) // @types **int }
// Takes values from the form data and puts them into a struct func mapForm(formStruct reflect.Value, form map[string][]string, formfile map[string][]*multipart.FileHeader, errors Errors) { if formStruct.Kind() == reflect.Ptr { formStruct = formStruct.Elem() } typ := formStruct.Type() for i := 0; i < typ.NumField(); i++ { typeField := typ.Field(i) structField := formStruct.Field(i) if typeField.Type.Kind() == reflect.Ptr && typeField.Anonymous { structField.Set(reflect.New(typeField.Type.Elem())) mapForm(structField.Elem(), form, formfile, errors) if reflect.DeepEqual(structField.Elem().Interface(), reflect.Zero(structField.Elem().Type()).Interface()) { structField.Set(reflect.Zero(structField.Type())) } } else if typeField.Type.Kind() == reflect.Struct { mapForm(structField, form, formfile, errors) } inputFieldName := parseFormName(typeField.Name, typeField.Tag.Get("form")) if len(inputFieldName) == 0 || !structField.CanSet() { continue } inputValue, exists := form[inputFieldName] if exists { numElems := len(inputValue) if structField.Kind() == reflect.Slice && numElems > 0 { sliceOf := structField.Type().Elem().Kind() slice := reflect.MakeSlice(structField.Type(), numElems, numElems) for i := 0; i < numElems; i++ { setWithProperType(sliceOf, inputValue[i], slice.Index(i), inputFieldName, errors) } formStruct.Field(i).Set(slice) } else { setWithProperType(typeField.Type.Kind(), inputValue[0], structField, inputFieldName, errors) } continue } inputFile, exists := formfile[inputFieldName] if !exists { continue } fhType := reflect.TypeOf((*multipart.FileHeader)(nil)) numElems := len(inputFile) if structField.Kind() == reflect.Slice && numElems > 0 && structField.Type().Elem() == fhType { slice := reflect.MakeSlice(structField.Type(), numElems, numElems) for i := 0; i < numElems; i++ { slice.Index(i).Set(reflect.ValueOf(inputFile[i])) } structField.Set(slice) } else if structField.Type() == fhType { structField.Set(reflect.ValueOf(inputFile[0])) } } }
func (c *Conn) GetAll(rowsSlicePtr interface{}, condition string, args ...interface{}) os.Error { sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr)) if sliceValue.Kind() != reflect.Slice { return os.NewError("needs a pointer to a slice") } sliceElementType := sliceValue.Type().Elem() condition = strings.TrimSpace(condition) if len(condition) > 0 { condition = fmt.Sprintf("where %v", condition) } resultsSlice, err := c.getResultsForQuery(getTableName(rowsSlicePtr), condition, args) if err != nil { return err } var a int println(reflect.ValueOf(a).CanAddr()) println(reflect.Zero(reflect.TypeOf(a)).CanAddr()) println(reflect.Zero(reflect.TypeOf(42)).Addr().String()) for _, results := range resultsSlice { newValue := reflect.Zero(sliceElementType) println("newValue = ", sliceElementType.String()) scanMapIntoStruct(newValue.Addr().Interface(), results) sliceValue.Set(reflect.Append(sliceValue, newValue)) } return nil }
func decodeArray(attr *AttributeValue, v reflect.Value) error { t := v.Type() if attr.NULL != nil || attr.L == nil { v.Set(reflect.Zero(t)) return nil } if t.Kind() == reflect.Slice { v.Set(reflect.MakeSlice(v.Type(), len(attr.L), len(attr.L))) } vlen := v.Len() if vlen == 0 { return nil } switch t.Elem().Kind() { case reflect.Interface: if t.Elem().NumMethod() != 0 { // TODO: If custom decoding hooks can be provided, support this return DecodeError{fmt.Sprintf("cannot decode into array of non-empty interface types: %s", v.Type().String()), false} } i := 0 alen := len(attr.L) for ; i < vlen && i < alen; i++ { if err := decodeAttribute(attr.L[i], v.Index(i)); err != nil { return err } } // zero out the rest for ; i < vlen; i++ { v.Index(i).Set(reflect.Zero(t.Elem())) } return nil default: i := 0 alen := len(attr.L) for ; i < vlen && i < alen; i++ { av := v.Index(i) if err := decodeAttribute(attr.L[i], av); err != nil { return err } if !av.IsValid() || !av.Type().AssignableTo(t.Elem()) { return DecodeError{fmt.Sprintf("could not assign list value %s to array element type %s", v.Type().String(), t.Elem().String()), false} } } for ; i < vlen; i++ { v.Index(i).Set(reflect.Zero(t.Elem())) } } return nil }
// RetrieveAsValue get the concrete generator result as reflect value. // If the result is invalid or does not pass the sieve there is no concrete // value and the property using the generator should be undecided. func (r *GenResult) RetrieveAsValue() (reflect.Value, bool) { if r.result != nil && (r.Sieve == nil || r.Sieve(r.result)) { return reflect.ValueOf(r.result), true } else if r.result == nil && r.Sieve != nil && r.Sieve(r.result) { return reflect.Zero(r.ResultType), true } return reflect.Zero(r.ResultType), false }
// safeNumericConvert converts numeric parameter val from js to the type that the function fn expects if its safe to do so. // This allows literals (int64) and the general js numeric form (float64) to be passed as parameters to go functions easily. func safeNumericConvert(fn reflect.Type, i int, val interface{}) reflect.Value { switch val.(type) { default: // Not a supported conversion return reflect.ValueOf(val) case float64, int64: // What type is the func expecting? var ptype reflect.Type switch { case fn.IsVariadic() && fn.NumIn() <= i+1: // This argument is variadic so use the variadics element type. ptype = fn.In(fn.NumIn() - 1).Elem() case fn.NumIn() > i: ptype = fn.In(i) } if f64, ok := val.(float64); ok { switch ptype.Kind() { case reflect.Float64: return reflect.ValueOf(val) case reflect.Float32: if reflect.Zero(ptype).OverflowFloat(f64) { // Not safe to convert return reflect.ValueOf(val) } return reflect.ValueOf(val).Convert(ptype) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: i64 := int64(f64) if float64(i64) != f64 { // Not safe to convert return reflect.ValueOf(val) } // The float represents an integer val = i64 default: // Not a supported conversion return reflect.ValueOf(val) } } i64 := val.(int64) switch ptype.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32: if !reflect.Zero(ptype).OverflowInt(i64) { return reflect.ValueOf(val).Convert(ptype) } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: if i64 > 0 && !reflect.Zero(ptype).OverflowUint(uint64(i64)) { return reflect.ValueOf(val).Convert(ptype) } } } // Not a supported conversion return reflect.ValueOf(val) }
func extractResponse(body []byte, results interface{}, structType reflect.Type) (err error) { if structType == nil { structType = validateResultsType(results) } // results is now guaranteed to be a pointer to a slice of structs. sliceValue := reflect.ValueOf(results).Elem() // decode JSON response body: yrsp := new(yqlResponse) err = json.Unmarshal(body, yrsp) if err != nil { // debugging info: log.Printf("response: %s\n", body) return } // Decode the Results map as either an array of objects or a single object: quote := yrsp.Query.Results["quote"] if quote == nil { // TODO(jsd): clear the sliceValue pointer to nil? return } switch t := quote.(type) { default: panic(errors.New("unexpected JSON result type for 'quote'")) case []interface{}: sl := sliceValue for j, n := range t { // Append to the slice for each array element: m := n.(map[string]interface{}) sl = reflect.Append(sl, reflect.Zero(structType)) el := sl.Index(j) for i := 0; i < structType.NumField(); i++ { f := structType.Field(i) if v, ok := m[f.Name]; ok { el.Field(i).Set(reflect.ValueOf(v)) } } } sliceValue.Set(sl) case map[string]interface{}: // Insert the only element of the slice: sl := reflect.Append(sliceValue, reflect.Zero(structType)) el0 := sl.Index(0) for i := 0; i < structType.NumField(); i++ { f := structType.Field(i) if v, ok := t[f.Name]; ok { el0.Field(i).Set(reflect.ValueOf(v)) } } sliceValue.Set(sl) } return }
/** * get func params * * @param funcType * @param */ func (r *ReflectRouter) getFuncArgs(funcType reflect.Type, context *HttpContext) []reflect.Value { argsNum := funcType.NumIn() args := make([]reflect.Value, argsNum, argsNum) for i := 0; i < argsNum; i++ { in := funcType.In(i) typeString := in.String() var argsValue reflect.Value switch typeString { case "*http.Request": argsValue = reflect.ValueOf(context.Request) case "http.Request": argsValue = reflect.ValueOf(context.Request).Elem() case "*url.URL": argsValue = reflect.ValueOf(context.Request.URL) case "url.URL": argsValue = reflect.ValueOf(context.Request.URL).Elem() case "*leafveingo.HttpContext": argsValue = reflect.ValueOf(context) case "leafveingo.HttpContext": argsValue = reflect.ValueOf(context).Elem() case "[]uint8": body := context.RequestBody() if nil != body { argsValue = reflect.ValueOf(body) } else { argsValue = reflect.Zero(in) } case "http.ResponseWriter": argsValue = reflect.ValueOf(context.RespWrite) case "LVSession.HttpSession": session, _ := context.Session(false) if nil != session { argsValue = reflect.ValueOf(session) } else { argsValue = reflect.Zero(in) } default: val, err := context.PackStructFormByRefType(in) if nil == err { argsValue = val } else { context.LVServer().Log().Debug(err.Error()) } } if reflect.Invalid == argsValue.Kind() { argsValue = reflect.Zero(in) } args[i] = argsValue } return args }
// IsEqual returns whether val1 is equal to val2 taking into account Pointers, Interfaces and their underlying types func IsEqual(val1, val2 interface{}) bool { v1 := reflect.ValueOf(val1) v2 := reflect.ValueOf(val2) if v1.Kind() == reflect.Ptr { v1 = v1.Elem() } if v2.Kind() == reflect.Ptr { v2 = v2.Elem() } if !v1.IsValid() && !v2.IsValid() { return true } switch v1.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: if v1.IsNil() { v1 = reflect.ValueOf(nil) } } switch v2.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: if v2.IsNil() { v2 = reflect.ValueOf(nil) } } v1Underlying := reflect.Zero(reflect.TypeOf(v1)).Interface() v2Underlying := reflect.Zero(reflect.TypeOf(v2)).Interface() if v1 == v1Underlying { if v2 == v2Underlying { goto CASE4 } else { goto CASE3 } } else { if v2 == v2Underlying { goto CASE2 } else { goto CASE1 } } CASE1: return reflect.DeepEqual(v1.Interface(), v2.Interface()) CASE2: return reflect.DeepEqual(v1.Interface(), v2) CASE3: return reflect.DeepEqual(v1, v2.Interface()) CASE4: return reflect.DeepEqual(v1, v2) }
// initField returns a valueBuilder based on the requested key. // If the key is a the magic tag _Val_, it returns itself. // If builder is a struct, it looks for a field of that name. // If builder is a map, it creates an entry for that key. // If buider is an array, it ignores the key and returns the next // element of the array. // If builder is a slice, it returns a newly appended element. // If the key cannot be resolved, it returns null. // If kind is Null, it initializes the field to the zero value. // Otherwise, it allocates memory as needed. func (builder *valueBuilder) initField(k string, kind byte) *valueBuilder { if k == MAGICTAG { if kind == Null { setZero(builder.val) return nil } return builder } switch builder.val.Kind() { case reflect.Struct: t := builder.val.Type() for i := 0; i < t.NumField(); i++ { if t.Field(i).Name == k { if kind == Null { setZero(builder.val.Field(i)) return nil } return newValueBuilder(builder.val.Field(i)) } } return nil case reflect.Map: t := builder.val.Type() if t.Key().Kind() != reflect.String { panic(NewBsonError("map index is not a string: %s", k)) } key := reflect.ValueOf(k) if kind == Null { zero := reflect.Zero(t.Elem()) builder.val.SetMapIndex(key, zero) return nil } return mapValueBuilder(t.Elem(), builder.val, key) case reflect.Array: if builder.index >= builder.val.Len() { panic(NewBsonError("array index %v out of bounds", builder.index)) } ind := builder.index builder.index++ if kind == Null { setZero(builder.val.Index(ind)) return nil } return newValueBuilder(builder.val.Index(ind)) case reflect.Slice: zero := reflect.Zero(builder.val.Type().Elem()) builder.val.Set(reflect.Append(builder.val, zero)) if kind == Null { return nil } return newValueBuilder(builder.val.Index(builder.val.Len() - 1)) } // Failsafe: this code is actually unreachable. panic(NewBsonError("internal error: unindexable type %v", builder.val.Type())) }
func resolve(event yaml_event_t, v reflect.Value, useNumber bool) (string, error) { val := string(event.value) if null_values[val] { v.Set(reflect.Zero(v.Type())) return yaml_NULL_TAG, nil } switch v.Kind() { case reflect.String: if useNumber && v.Type() == numberType { tag, i := resolveInterface(event, useNumber) if n, ok := i.(Number); ok { v.Set(reflect.ValueOf(n)) return tag, nil } return "", errors.New("Not a Number: " + reflect.TypeOf(i).String()) } return resolve_string(val, v, event) case reflect.Bool: return resolve_bool(val, v) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return resolve_int(val, v, useNumber) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return resolve_uint(val, v, useNumber) case reflect.Float32, reflect.Float64: return resolve_float(val, v, useNumber) case reflect.Interface: _, i := resolveInterface(event, useNumber) if i != nil { v.Set(reflect.ValueOf(i)) } else { v.Set(reflect.Zero(v.Type())) } case reflect.Struct: return resolve_time(val, v) case reflect.Slice: if v.Type() != byteSliceType { return "", errors.New("Cannot resolve into " + v.Type().String()) } b, err := decode_binary(event.value) if err != nil { return "", err } v.Set(reflect.ValueOf(b)) default: return "", errors.New("Resolve failed for " + v.Kind().String()) } return yaml_STR_TAG, nil }
func resolve(event yaml_event_t, v reflect.Value, useNumber bool) (string, error) { val := string(event.value) if null_values[val] { v.Set(reflect.Zero(v.Type())) return yaml_NULL_TAG, nil } switch v.Kind() { case reflect.String: if useNumber && v.Type() == numberType { tag, i := resolveInterface(event, useNumber) if n, ok := i.(Number); ok { v.Set(reflect.ValueOf(n)) return tag, nil } return "", fmt.Errorf("Not a number: '%s' at %s", event.value, event.start_mark) } return resolve_string(val, v, event) case reflect.Bool: return resolve_bool(val, v, event) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return resolve_int(val, v, useNumber, event) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return resolve_uint(val, v, useNumber, event) case reflect.Float32, reflect.Float64: return resolve_float(val, v, useNumber, event) case reflect.Interface: _, i := resolveInterface(event, useNumber) if i != nil { v.Set(reflect.ValueOf(i)) } else { v.Set(reflect.Zero(v.Type())) } case reflect.Struct: return resolve_time(val, v, event) case reflect.Slice: if v.Type() != byteSliceType { return "", fmt.Errorf("Cannot resolve %s into %s at %s", val, v.String(), event.start_mark) } b, err := decode_binary(event.value, event) if err != nil { return "", err } v.Set(reflect.ValueOf(b)) default: return "", fmt.Errorf("Unknown resolution for '%s' using %s at %s", val, v.String(), event.start_mark) } return yaml_STR_TAG, nil }
// Field returns the named field within the given argument. // The argument should be a struct or *struct. // All errors are silently reported by returning a zero value. func Field(i interface{}, name string) reflect.Value /*, error*/ { if !IsStructOrStructPtr(i) { return reflect.Zero(TypeOf(i)) //, errNotAStruct } field := ValueOf(i).FieldByName(name) if !field.IsValid() { return reflect.Zero(TypeOf(i)) //, errUnknownField } return field //, nil }
func ZeroProperties(structValue reflect.Value) { typ := structValue.Type() for i := 0; i < structValue.NumField(); i++ { field := typ.Field(i) if field.PkgPath != "" { // The field is not exported so just skip it. continue } fieldValue := structValue.Field(i) switch fieldValue.Kind() { case reflect.Bool, reflect.String, reflect.Slice, reflect.Int, reflect.Uint: fieldValue.Set(reflect.Zero(fieldValue.Type())) case reflect.Interface: if fieldValue.IsNil() { break } // We leave the pointer intact and zero out the struct that's // pointed to. fieldValue = fieldValue.Elem() if fieldValue.Kind() != reflect.Ptr { panic(fmt.Errorf("can't zero field %q: interface refers to a non-pointer", field.Name)) } if fieldValue.Type().Elem().Kind() != reflect.Struct { panic(fmt.Errorf("can't zero field %q: interface points to a non-struct", field.Name)) } fallthrough case reflect.Ptr: switch fieldValue.Type().Elem().Kind() { case reflect.Struct: if fieldValue.IsNil() { break } ZeroProperties(fieldValue.Elem()) case reflect.Bool, reflect.String: fieldValue.Set(reflect.Zero(fieldValue.Type())) default: panic(fmt.Errorf("can't zero field %q: points to a %s", field.Name, fieldValue.Elem().Kind())) } case reflect.Struct: ZeroProperties(fieldValue) default: panic(fmt.Errorf("unexpected kind for property struct field %q: %s", field.Name, fieldValue.Kind())) } } }
func ByteSliceConvert(p *Params, n string, typ reflect.Type) reflect.Value { file := getMultipartFile(p, n) if file == nil { return reflect.Zero(typ) } bs, err := ioutil.ReadAll(file) if err != nil { WARN.Println("read all multipart file error,", err) return reflect.Zero(typ) } return reflect.ValueOf(bs) }
/* ForAll creates a property that requires the check condition to be true for all values, if the condition falsiies the generated values will be shrinked. "condition" has to be a function with the same number of parameters as the provided generators "gens". The function may return a simple bool (true means that the condition has passed), a string (empty string means that condition has passed), a *PropResult, or one of former combined with an error. */ func ForAll(condition interface{}, gens ...gopter.Gen) gopter.Prop { callCheck, err := checkConditionFunc(condition, len(gens)) if err != nil { return ErrorProp(err) } return gopter.SaveProp(func(genParams *gopter.GenParameters) *gopter.PropResult { genResults := make([]*gopter.GenResult, len(gens)) values := make([]reflect.Value, len(gens)) var ok bool for i, gen := range gens { result := gen(genParams) genResults[i] = result values[i], ok = result.RetrieveAsValue() if !ok { return &gopter.PropResult{ Status: gopter.PropUndecided, } } } result := callCheck(values) if result.Success() { for i, genResult := range genResults { result = result.AddArgs(gopter.NewPropArg(genResult, 0, values[i].Interface(), values[i].Interface())) } } else { for i, genResult := range genResults { nextResult, nextValue := shrinkValue(genParams.MaxShrinkCount, genResult, values[i].Interface(), result, func(v interface{}) *gopter.PropResult { shrinkedOne := make([]reflect.Value, len(values)) copy(shrinkedOne, values) if v == nil { shrinkedOne[i] = reflect.Zero(values[i].Type()) } else { shrinkedOne[i] = reflect.ValueOf(v) } return callCheck(shrinkedOne) }) result = nextResult if nextValue == nil { values[i] = reflect.Zero(values[i].Type()) } else { values[i] = reflect.ValueOf(nextValue) } } } return result }) }
func mapToArrayInner(data reflect.Value, target reflect.Value, tag string) error { //处理data是个nil的问题 if data.IsValid() == false { target.Set(reflect.Zero(target.Type())) return nil } //处理data是多层嵌套的问题 dataKind := data.Type().Kind() if dataKind == reflect.Interface { return mapToArrayInner(data.Elem(), target, tag) } else if dataKind == reflect.Ptr { return mapToArrayInner(data.Elem(), target, tag) } //根据target是多层嵌套的问题 targetType := getDataTagInfo(target.Type(), tag) if targetType.kind == TypeKind.PTR { return mapToPtr(data, target, tag) } else if targetType.kind == TypeKind.INTERFACE { return mapToInterface(data, target, tag) } //处理data是个空字符串 if dataKind == reflect.String && data.String() == "" { target.Set(reflect.Zero(target.Type())) return nil } if targetType.kind == TypeKind.BOOL { return mapToBool(data, target) } else if targetType.kind == TypeKind.INT { return mapToInt(data, target) } else if targetType.kind == TypeKind.UINT { return mapToUint(data, target) } else if targetType.kind == TypeKind.FLOAT { return mapToFloat(data, target) } else if targetType.kind == TypeKind.STRING { return mapToString(data, target) } else if targetType.kind == TypeKind.ARRAY { return mapToArray(data, target, tag) } else if targetType.kind == TypeKind.MAP { return mapToMap(data, target, tag) } else if targetType.kind == TypeKind.STRUCT { if targetType.isTimeType { return mapToTime(data, target) } else { return mapToStruct(data, target, targetType, tag) } } else { return errors.New("unkown target type " + target.Type().String()) } }