func (scope *Scope) getColumnsAsScope(column string) *Scope { values := scope.IndirectValue() switch values.Kind() { case reflect.Slice: modelType := values.Type().Elem() if modelType.Kind() == reflect.Ptr { modelType = modelType.Elem() } fieldStruct, _ := modelType.FieldByName(column) var columns reflect.Value if fieldStruct.Type.Kind() == reflect.Slice || fieldStruct.Type.Kind() == reflect.Ptr { columns = reflect.New(reflect.SliceOf(reflect.PtrTo(fieldStruct.Type.Elem()))).Elem() } else { columns = reflect.New(reflect.SliceOf(reflect.PtrTo(fieldStruct.Type))).Elem() } for i := 0; i < values.Len(); i++ { column := reflect.Indirect(values.Index(i)).FieldByName(column) if column.Kind() == reflect.Ptr { column = column.Elem() } if column.Kind() == reflect.Slice { for i := 0; i < column.Len(); i++ { columns = reflect.Append(columns, column.Index(i).Addr()) } } else { columns = reflect.Append(columns, column.Addr()) } } return scope.New(columns.Interface()) case reflect.Struct: return scope.New(values.FieldByName(column).Addr().Interface()) } return nil }
// mapEncodeScratch returns a new reflect.Value matching the map's value type, // and a structPointer suitable for passing to an encoder or sizer. func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) { // Prepare addressable doubly-indirect placeholders for the key and value types. // This is needed because the element-type encoders expect **T, but the map iteration produces T. keycopy = reflect.New(mapType.Key()).Elem() // addressable K keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K keyptr.Set(keycopy.Addr()) // keybase = toStructPointer(keyptr.Addr()) // **K // Value types are more varied and require special handling. switch mapType.Elem().Kind() { case reflect.Slice: // []byte var dummy []byte valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte valbase = toStructPointer(valcopy.Addr()) case reflect.Ptr: // message; the generated field type is map[K]*Msg (so V is *Msg), // so we only need one level of indirection. valcopy = reflect.New(mapType.Elem()).Elem() // addressable V valbase = toStructPointer(valcopy.Addr()) default: // everything else valcopy = reflect.New(mapType.Elem()).Elem() // addressable V valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V valptr.Set(valcopy.Addr()) // valbase = toStructPointer(valptr.Addr()) // **V } return }
func makeDecoder(typ reflect.Type, tags tags) (dec decoder, err error) { kind := typ.Kind() switch { case typ == rawValueType: return decodeRawValue, nil case typ.Implements(decoderInterface): return decodeDecoder, nil case kind != reflect.Ptr && reflect.PtrTo(typ).Implements(decoderInterface): return decodeDecoderNoPtr, nil case typ.AssignableTo(reflect.PtrTo(bigInt)): return decodeBigInt, nil case typ.AssignableTo(bigInt): return decodeBigIntNoPtr, nil case isUint(kind): return decodeUint, nil case kind == reflect.Bool: return decodeBool, nil case kind == reflect.String: return decodeString, nil case kind == reflect.Slice || kind == reflect.Array: return makeListDecoder(typ, tags) case kind == reflect.Struct: return makeStructDecoder(typ) case kind == reflect.Ptr: if tags.nilOK { return makeOptionalPtrDecoder(typ) } return makePtrDecoder(typ) case kind == reflect.Interface: return decodeInterface, nil default: return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ) } }
// makeWriter creates a writer function for the given type. func makeWriter(typ reflect.Type) (writer, error) { kind := typ.Kind() switch { case typ.Implements(encoderInterface): return writeEncoder, nil case kind != reflect.Ptr && reflect.PtrTo(typ).Implements(encoderInterface): return writeEncoderNoPtr, nil case kind == reflect.Interface: return writeInterface, nil case typ.AssignableTo(reflect.PtrTo(bigInt)): return writeBigIntPtr, nil case typ.AssignableTo(bigInt): return writeBigIntNoPtr, nil case isUint(kind): return writeUint, nil case kind == reflect.Bool: return writeBool, nil case kind == reflect.String: return writeString, nil case kind == reflect.Slice && isByte(typ.Elem()): return writeBytes, nil case kind == reflect.Array && isByte(typ.Elem()): return writeByteArray, nil case kind == reflect.Slice || kind == reflect.Array: return makeSliceWriter(typ) case kind == reflect.Struct: return makeStructWriter(typ) case kind == reflect.Ptr: return makePtrWriter(typ) default: return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ) } }
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 }
func (p *model) GetValuesForSqlRowScan(cols []string) []interface{} { var values = make([]interface{}, len(cols)) for index, column := range cols { if field, ok := p.Fields[column]; ok { if field.IsJsonb() { var vs []byte values[index] = &vs } else if field.Field.Kind() == reflect.Ptr { values[index] = field.Field.Addr().Interface() } else if field.Field.Kind() == reflect.String { values[index] = reflect.New(reflect.PtrTo(reflect.TypeOf(""))).Interface() } else if field.Field.Kind() == reflect.Struct { switch field.Field.Type().String() { // case "time.Time": // values[index] = reflect.New(reflect.PtrTo(reflect.TypeOf(""))).Interface() default: values[index] = reflect.New(reflect.PtrTo(field.Field.Type())).Interface() } } else { values[index] = reflect.New(reflect.PtrTo(field.Field.Type())).Interface() } } else { var i interface{} values[index] = &i } } return values }
func (jd *joinDeclaration) Into(dest interface{}) *joinDeclaration { var r *Relation rt := reflect.TypeOf(r).Elem() dt := reflect.TypeOf(dest) if !dt.Implements(rt) { panic(fmt.Sprintf("Into() param: %#v, type: %v"+ ", does not implement Relation", dest, dt)) } jd.into = dest.(Relation) var out reflect.Type if jd.selectWhereFunc != nil { out = reflect.TypeOf(jd.selectWhereFunc).Out(0) } else if len(jd.sources) == 1 { out = reflect.PtrTo(jd.sources[0].TupleType()) } else { panic(fmt.Sprintf("unexpected Into() join declaration: %#v", jd)) } if jd.selectWhereFlat { if out != dt { panic(fmt.Sprintf("Into() param: %#v, type: %v, does not match"+ " output type: %v", dest, dt, out)) } } else { if out != jd.into.TupleType() && out != reflect.PtrTo(jd.into.TupleType()) { panic(fmt.Sprintf("Into() param: %#v, type: %v, does not match"+ " tuple type: %v", dest, dt, out)) } } return jd }
func checkUnaryExpr(ctx *Ctx, unary *ast.UnaryExpr, env *Env) (*UnaryExpr, []error) { aexpr := &UnaryExpr{UnaryExpr: unary} x, errs := CheckExpr(ctx, unary.X, env) if errs == nil || x.IsConst() { if t, err := expectSingleType(ctx, x.KnownType(), x); err != nil { errs = append(errs, err) } else if unary.Op == token.AND { // address of if !isAddressableOrCompositeLit(x) { printableX := fakeCheckExpr(unary.X, env) printableX.setKnownType(knownType{t}) errs = append(errs, ErrInvalidAddressOf{at(ctx, printableX)}) } t := x.KnownType()[0] if ct, ok := t.(ConstType); ok { if ct == ConstNil { errs = append(errs, ErrUntypedNil{at(ctx, x)}) } else { ptrT := reflect.PtrTo(unhackType(ct.DefaultPromotion())) aexpr.knownType = knownType{ptrT} } } else { ptrT := reflect.PtrTo(unhackType(t)) aexpr.knownType = knownType{ptrT} } aexpr.X = x } else if unary.Op == token.ARROW { // <- if (t.Kind() != reflect.Chan) || (t.ChanDir()|reflect.RecvDir == 0) { errs = append(errs, ErrInvalidRecvFrom{at(ctx, x)}) } } else { aexpr.X = x // All numeric and bool unary expressions do not change type aexpr.knownType = knownType(x.KnownType()) if x.IsConst() { if ct, ok := t.(ConstType); ok { c, moreErrs := evalConstUnaryExpr(ctx, aexpr, x, ct) if moreErrs != nil { errs = append(errs, moreErrs...) } aexpr.constValue = c } else { c, moreErrs := evalConstTypedUnaryExpr(ctx, aexpr, x) if moreErrs != nil { errs = append(errs, moreErrs...) } aexpr.constValue = c } } else { if !isUnaryOpDefinedOn(unary.Op, t) { errs = append(errs, ErrInvalidUnaryOperation{at(ctx, unary)}) } } } } aexpr.X = x return aexpr, errs }
func implementsInterface(t reflect.Type) bool { return t.Implements(decoderType) || reflect.PtrTo(t).Implements(decoderType) || t.Implements(setterType) || reflect.PtrTo(t).Implements(setterType) || t.Implements(unmarshalerType) || reflect.PtrTo(t).Implements(unmarshalerType) }
// newTypeEncoder constructs an encoderFunc for a type. // The returned encoder only checks CanAddr when allowAddr is true. func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc { if t.Implements(marshalerType) { return marshalerEncoder } if t.Kind() != reflect.Ptr && allowAddr { if reflect.PtrTo(t).Implements(marshalerType) { return newCondAddrEncoder(addrMarshalerEncoder, newTypeEncoder(t, false)) } } if t.Implements(jsonMarshalerType) { return jsonMarshalerEncoder } if t.Kind() != reflect.Ptr && allowAddr { if reflect.PtrTo(t).Implements(jsonMarshalerType) { return newCondAddrEncoder(addrJsonMarshalerEncoder, newTypeEncoder(t, false)) } } if t.Implements(textMarshalerType) { return textMarshalerEncoder } if t.Kind() != reflect.Ptr && allowAddr { if reflect.PtrTo(t).Implements(textMarshalerType) { return newCondAddrEncoder(addrTextMarshalerEncoder, newTypeEncoder(t, false)) } } switch t.Kind() { case reflect.Bool: return boolEncoder case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return intEncoder case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return uintEncoder case reflect.Float32: return float32Encoder case reflect.Float64: return float64Encoder case reflect.String: return stringEncoder case reflect.Interface: return interfaceEncoder case reflect.Struct: return newStructEncoder(t) case reflect.Map: return newMapEncoder(t) case reflect.Slice: return newSliceEncoder(t) case reflect.Array: return newArrayEncoder(t) case reflect.Ptr: return newPtrEncoder(t) default: return unsupportedTypeEncoder } }
// A simple check of type comparison. Ptr to a struct and struct are // considered compatible. This is useful mostly for the cases where // we have interface implementations func TypeMatch(this interface{}, that interface{}) bool { t1 := reflect.TypeOf(this) t2 := reflect.TypeOf(that) if t1 == t2 { return true } if reflect.PtrTo(t1) == t2 || t1 == reflect.PtrTo(t2) { return true } return false }
func isRecursive(v reflect.Value) bool { ind := reflect.Indirect(v) t := v.Type() if ind.Kind() != reflect.Struct { return false } for i := 0; i < ind.Type().NumField(); i++ { ft := ind.Field(i).Type() return ft == t || ft == reflect.PtrTo(t) || t.AssignableTo(ft) || reflect.PtrTo(t).AssignableTo(ft) } return false }
func (i *Inception) wantMarshal(si *StructInfo) bool { if si.Options.SkipEncoder { return false } typ := si.Typ mlx := typ.Implements(marshalerFasterType) || reflect.PtrTo(typ).Implements(marshalerFasterType) mlstd := typ.Implements(marshalerType) || reflect.PtrTo(typ).Implements(marshalerType) if mlstd && !mlx { // structure has MarshalJSON, but not our faster version -- skip it. return false } return true }
/* Find sets the fields of values to the matches of the patterns specified for them in Compile. values must be a pointer to the same type of struct as used in Compile. Returns true if there is at least 1 field match. Fields for which no match is found will not be modified, so you can specify default values by just setting fields on values before passing it to this method. */ func (r *TypedRegexp) Find(s string, values interface{}) (found bool) { t := reflect.TypeOf(r.captureGroups) ptr := reflect.ValueOf(values) if ptr.Type() != reflect.PtrTo(t) { panic(fmt.Errorf("values must be %s, is %s", reflect.PtrTo(t), ptr.Type())) } submatches := r.pattern.FindStringSubmatch(s) if len(submatches) == 0 { return false } r.assignSubmatchesToStruct(submatches, &ptr) return true }
// validateType guarantees that the value is valid and assignable to the type. func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value { if !value.IsValid() { if typ == nil || canBeNil(typ) { // An untyped nil interface{}. Accept as a proper nil value. return reflect.Zero(typ) } s.errorf("invalid value; expected %s", typ) } if typ != nil && !value.Type().AssignableTo(typ) { if value.Kind() == reflect.Interface && !value.IsNil() { value = value.Elem() if value.Type().AssignableTo(typ) { return value } // fallthrough } // Does one dereference or indirection work? We could do more, as we // do with method receivers, but that gets messy and method receivers // are much more constrained, so it makes more sense there than here. // Besides, one is almost always all you need. switch { case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ): value = value.Elem() if !value.IsValid() { s.errorf("dereference of nil pointer of type %s", typ) } case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr(): value = value.Addr() default: s.errorf("wrong type for value; expected %s; got %s", typ, value.Type()) } } return value }
func TestCoverage(t *testing.T) { for kind, apiType := range kapi.Scheme.KnownTypes("") { if !strings.Contains(apiType.PkgPath(), "openshift/origin") { continue } if strings.HasSuffix(kind, "List") { continue } ptrType := reflect.PtrTo(apiType) if _, exists := Validator.typeToValidator[ptrType]; !exists { allowed := false for _, exception := range KnownValidationExceptions { if ptrType == exception { allowed = true break } } for _, exception := range MissingValidationExceptions { if ptrType == exception { allowed = true } } if !allowed { t.Errorf("%v is not registered. Look in pkg/api/validation/register.go.", apiType) } } } }
func TestDescriberCoverage(t *testing.T) { c := &client.Client{} main: for _, apiType := range kapi.Scheme.KnownTypes("") { if !strings.Contains(apiType.PkgPath(), "openshift/origin") { continue } // we don't describe lists if strings.HasSuffix(apiType.Name(), "List") { continue } ptrType := reflect.PtrTo(apiType) for _, exception := range DescriberCoverageExceptions { if ptrType == exception { continue main } } for _, exception := range MissingDescriberCoverageExceptions { if ptrType == exception { continue main } } _, ok := DescriberFor(apiType.Name(), c, &ktestclient.Fake{}, "") if !ok { t.Errorf("missing printer for %v. Check pkg/cmd/cli/describe/describer.go", apiType) } } }
// UnsafeReflectValue converts the passed reflect.Value into a one that bypasses // the typical safety restrictions preventing access to unaddressable and // unexported data. It works by digging the raw pointer to the underlying // value out of the protected value and generating a new unprotected (unsafe) // reflect.Value to it. // // This allows us to check for implementations of the Stringer and error // interfaces to be used for pretty printing ordinarily unaddressable and // inaccessible values such as unexported struct fields. func UnsafeReflectValue(v reflect.Value) (rv reflect.Value) { indirects := 1 vt := v.Type() upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr) rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag)) if rvf&flagIndir != 0 { vt = reflect.PtrTo(v.Type()) indirects++ } else if offsetScalar != 0 { // The value is in the scalar field when it's not one of the // reference types. switch vt.Kind() { case reflect.Uintptr: case reflect.Chan: case reflect.Func: case reflect.Map: case reflect.Ptr: case reflect.UnsafePointer: default: upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetScalar) } } pv := reflect.NewAt(vt, upv) rv = pv for i := 0; i < indirects; i++ { rv = rv.Elem() } return rv }
// implementsInterface reports whether the type implements the // gobEncoder/gobDecoder interface. // It also returns the number of indirections required to get to the // implementation. func implementsInterface(typ, gobEncDecType reflect.Type) (success bool, indir int8) { if typ == nil { return } rt := typ // The type might be a pointer and we need to keep // dereferencing to the base type until we find an implementation. for { if rt.Implements(gobEncDecType) { return true, indir } if p := rt; p.Kind() == reflect.Ptr { indir++ if indir > 100 { // insane number of indirections return false, 0 } rt = p.Elem() continue } break } // No luck yet, but if this is a base type (non-pointer), the pointer might satisfy. if typ.Kind() != reflect.Ptr { // Not a pointer, but does the pointer work? if reflect.PtrTo(typ).Implements(gobEncDecType) { return true, -1 } } return false, 0 }
func tryValidate(val reflect.Value) error { t := val.Type() var validator Validator if t.Implements(tValidator) { validator = val.Interface().(Validator) } else if reflect.PtrTo(t).Implements(tValidator) { val = pointerize(reflect.PtrTo(t), t, val) validator = val.Interface().(Validator) } if validator == nil { return nil } return validator.Validate() }
func parseFlagField(field reflect.StructField, fieldVal reflect.Value) *Option { checkTags(field, flagTag) checkExported(field, flagTag) names := parseCommaNames(field.Tag.Get(flagTag)) if len(names) == 0 { panicCommand("at least one flag name must be specified (field %s)", field.Name) } opt := &Option{ Names: names, Flag: true, Description: field.Tag.Get(descriptionTag), } if field.Type.Implements(decoderT) { opt.Decoder = fieldVal.Interface().(OptionDecoder) } else if fieldVal.CanAddr() && reflect.PtrTo(field.Type).Implements(decoderT) { opt.Decoder = fieldVal.Addr().Interface().(OptionDecoder) } else { switch field.Type.Kind() { case reflect.Bool: opt.Decoder = NewFlagDecoder(fieldVal.Addr().Interface().(*bool)) case reflect.Int: opt.Decoder = NewFlagAccumulator(fieldVal.Addr().Interface().(*int)) opt.Plural = true default: panicCommand("field type not valid as a flag -- did you mean to use %q instead? (field %s)", "option", field.Name) } } opt.validate() return opt }
// gobDecodeOpFor returns the op for a type that is known to implement // GobDecoder. func (dec *Decoder) gobDecodeOpFor(ut *userTypeInfo) (*decOp, int) { rcvrType := ut.user if ut.decIndir == -1 { rcvrType = reflect.PtrTo(rcvrType) } else if ut.decIndir > 0 { for i := int8(0); i < ut.decIndir; i++ { rcvrType = rcvrType.Elem() } } var op decOp op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { // Caller has gotten us to within one indirection of our value. if i.indir > 0 { if *(*unsafe.Pointer)(p) == nil { *(*unsafe.Pointer)(p) = unsafe.Pointer(reflect.New(ut.base).Pointer()) } } // Now p is a pointer to the base type. Do we need to climb out to // get to the receiver type? var v reflect.Value if ut.decIndir == -1 { v = reflect.NewAt(rcvrType, unsafe.Pointer(&p)).Elem() } else { v = reflect.NewAt(rcvrType, p).Elem() } state.dec.decodeGobDecoder(ut, state, v) } return &op, int(ut.indir) }
func makeListDecoder(typ reflect.Type, tag tags) (decoder, error) { etype := typ.Elem() if etype.Kind() == reflect.Uint8 && !reflect.PtrTo(etype).Implements(decoderInterface) { if typ.Kind() == reflect.Array { return decodeByteArray, nil } else { return decodeByteSlice, nil } } etypeinfo, err := cachedTypeInfo1(etype, tags{}) if err != nil { return nil, err } var dec decoder switch { case typ.Kind() == reflect.Array: dec = func(s *Stream, val reflect.Value) error { return decodeListArray(s, val, etypeinfo.decoder) } case tag.tail: // A slice with "tail" tag can occur as the last field // of a struct and is upposed to swallow all remaining // list elements. The struct decoder already called s.List, // proceed directly to decoding the elements. dec = func(s *Stream, val reflect.Value) error { return decodeSliceElems(s, val, etypeinfo.decoder) } default: dec = func(s *Stream, val reflect.Value) error { return decodeListSlice(s, val, etypeinfo.decoder) } } return dec, nil }
// TODO: update this to honor sorting func (sr *SQL) FindDefault(r *Request, rp RequestParams) ([]*Record, error) { p := rp.Paginator a := r.API vs := reflect.New(reflect.SliceOf(reflect.PtrTo(sr.Type))).Interface() offset_and_limit := "" if p.ShouldPaginate { offset_and_limit = fmt.Sprintf("LIMIT %d OFFSET %d", p.MaxPerPage, p.CurPage*p.MaxPerPage, ) } q := fmt.Sprintf( "SELECT * FROM %s %s", sr.Table, offset_and_limit, ) a.Logger.Debugf("Query: %#v\n", q) err := meddler.QueryAll( sr.DB, vs, q, ) if err == sql.ErrNoRows { return nil, nil } if err != nil { return nil, err } return sr.ConvertInterfaceSliceToRecordSlice(vs), err }
func (sr *SQL) FindManyByField(r *Request, rp RequestParams, field, value string) ([]*Record, error) { p := rp.Paginator vs := reflect.New(reflect.SliceOf(reflect.PtrTo(sr.Type))).Interface() field, err := sr.GetTableFieldFromStructField(field) if err != nil { return nil, err } offset_and_limit := "" if p.ShouldPaginate { offset_and_limit = fmt.Sprintf("LIMIT %d OFFSET %d", p.MaxPerPage, p.CurPage*p.MaxPerPage, ) } // TODO: find a way to parameterize field in this query // right now, field is always a trusted string, but some // later relationship behaviors might change that, and it's // better to be safe than sorry // dropping in ? instead of field does not work :/ q := fmt.Sprintf("SELECT * FROM %s WHERE %s=? %s", sr.Table, field, offset_and_limit) r.API.Logger.Debugf("Query: %#v %#v\n", q, value) err = meddler.QueryAll( sr.DB, vs, q, value, ) if err == sql.ErrNoRows { return nil, nil } r.API.Logger.Debugf("RES: %#v\n", vs) return sr.ConvertInterfaceSliceToRecordSlice(vs), err }
// NextPage retrieves a sequence of items from the iterator and appends them // to slicep, which must be a pointer to a slice of the iterator's item type. // Exactly p.pageSize items will be appended, unless fewer remain. // // The first return value is the page token to use for the next page of items. // If empty, there are no more pages. Aside from checking for the end of the // iteration, the returned page token is only needed if the iteration is to be // resumed a later time, in another context (possibly another process). // // The second return value is non-nil if an error occurred. It will never be // the special iterator sentinel value Done. To recognize the end of the // iteration, compare nextPageToken to the empty string. // // It is possible for NextPage to return a single zero-length page along with // an empty page token when there are no more items in the iteration. func (p *Pager) NextPage(slicep interface{}) (nextPageToken string, err error) { p.pageInfo.nextPageCalled = true if p.pageInfo.err != nil { return "", p.pageInfo.err } if p.pageInfo.nextCalled { p.pageInfo.err = errMixed return "", p.pageInfo.err } if p.pageInfo.bufLen() > 0 { return "", errors.New("must call NextPage with an empty buffer") } // The buffer must be empty here, so takeBuf is a no-op. We call it just to get // the buffer's type. wantSliceType := reflect.PtrTo(reflect.ValueOf(p.pageInfo.takeBuf()).Type()) if slicep == nil { return "", errors.New("nil passed to Pager.NextPage") } vslicep := reflect.ValueOf(slicep) if vslicep.Type() != wantSliceType { return "", fmt.Errorf("slicep should be of type %s, got %T", wantSliceType, slicep) } for p.pageInfo.bufLen() < p.pageSize { if err := p.pageInfo.fill(p.pageSize - p.pageInfo.bufLen()); err != nil { p.pageInfo.err = err return "", p.pageInfo.err } if p.pageInfo.Token == "" { break } } e := vslicep.Elem() e.Set(reflect.AppendSlice(e, reflect.ValueOf(p.pageInfo.takeBuf()))) return p.pageInfo.Token, nil }
// CreateRequestMessage creates the request json message using the given input. // Note, the input *MUST* be a pointer to a valid backend type that this // client recognises. func (cs *ClientServerImpl) CreateRequestMessage(input interface{}) ([]byte, error) { msg := &RequestMessage{} recognizedTypes := cs.GetRecognizedTypes() for typeStr, typeVal := range recognizedTypes { if reflect.TypeOf(input) == reflect.PtrTo(typeVal) { msg.Type = typeStr break } } if msg.Type == "" { return nil, &UnrecognizedWSRequestType{reflect.TypeOf(input).String()} } messageData, err := jsonutil.BuildJSON(input) if err != nil { return nil, &NotMarshallableWSRequest{msg.Type, err} } msg.Message = json.RawMessage(messageData) send, err := json.Marshal(msg) if err != nil { return nil, &NotMarshallableWSRequest{msg.Type, err} } return send, nil }
func getSetter(outt reflect.Type, out reflect.Value) Setter { setterMutex.RLock() style := setterStyle[outt] setterMutex.RUnlock() if style == setterNone { return nil } if style == setterUnknown { setterMutex.Lock() defer setterMutex.Unlock() if outt.Implements(setterIface) { setterStyle[outt] = setterType } else if reflect.PtrTo(outt).Implements(setterIface) { setterStyle[outt] = setterAddr } else { setterStyle[outt] = setterNone return nil } style = setterStyle[outt] } if style == setterAddr { if !out.CanAddr() { return nil } out = out.Addr() } else if outt.Kind() == reflect.Ptr && out.IsNil() { out.Set(reflect.New(outt.Elem())) } return out.Interface().(Setter) }
func ptrTo(v interface{}) reflect.Type { typ := reflect.TypeOf(v) if typ.Kind() != reflect.Ptr { typ = reflect.PtrTo(typ) } return typ }
func TestPrinterCoverage(t *testing.T) { printer := NewHumanReadablePrinter(kctl.PrintOptions{}) main: for _, apiType := range kapi.Scheme.KnownTypes(api.SchemeGroupVersion) { if !strings.Contains(apiType.PkgPath(), "github.com/openshift/origin") || strings.Contains(apiType.PkgPath(), "github.com/openshift/origin/vendor/") { continue } ptrType := reflect.PtrTo(apiType) for _, exception := range PrinterCoverageExceptions { if ptrType == exception { continue main } } for _, exception := range MissingPrinterCoverageExceptions { if ptrType == exception { continue main } } newStructValue := reflect.New(apiType) newStruct := newStructValue.Interface() if err := printer.PrintObj(newStruct.(runtime.Object), ioutil.Discard); (err != nil) && strings.Contains(err.Error(), "error: unknown type ") { t.Errorf("missing printer for %v. Check pkg/cmd/cli/describe/printer.go", apiType) } } }