Example #1
1
// return the next n permuations, if n>p.Left(),return all the left permuations
// if all permutaions generated or n is illegal(n<=0),return a empty slice
func (p *Permutator) NextN(count int) interface{} {
	if count <= 0 || p.left() == 0 {
		return reflect.MakeSlice(reflect.SliceOf(p.value.Type()), 0, 0).Interface()
	}

	cap := p.left()
	if cap > count {
		cap = count
	}

	result := reflect.MakeSlice(reflect.SliceOf(p.value.Type()), cap, cap)

	length := 0
	for index := 0; index < cap; index++ {
		if _, ok := p.Next(); ok {
			length++
			list := p.copySliceValue()
			result.Index(index).Set(list)
		}
	}

	list := reflect.MakeSlice(result.Type(), length, length)
	reflect.Copy(list, result)

	return list.Interface()
}
// FindAll finds the first len(values) matches of the regex in s.
// valuesSlice must be a slice of structs (or pointers to structs) of the same type as passed to Compile.
// Nil elements are skipped.
// Returns the number of matches found. Note that not all valuesSlice[:n] may have been
// set from the regexp, if some of the matches didn't match on any of the fields.
//
// Calling FindAll with a slice of len 1 is basically same as passing a pointer to that struct
// to Find().
func (r *TypedRegexp) FindAll(s string, valuesSlice interface{}) (n int) {
	t := reflect.TypeOf(r.captureGroups)
	slice := reflect.ValueOf(valuesSlice)

	sliceType := slice.Type()
	expectedType := reflect.SliceOf(t)
	expectedPtrType := reflect.SliceOf(reflect.PtrTo(t))
	if sliceType != expectedType && sliceType != expectedPtrType {
		panic(fmt.Errorf("values must be %s or %s, is %s", expectedType, expectedPtrType, sliceType))
	}

	if slice.Len() == 0 {
		return 0
	}

	allSubmatches := r.pattern.FindAllStringSubmatch(s, slice.Len())
	n = len(allSubmatches)
	for submatchIndex, submatches := range allSubmatches {
		v := slice.Index(submatchIndex)

		if v.Kind() == reflect.Ptr && v.IsNil() {
			continue
		}

		r.assignSubmatchesToStruct(submatches, &v)
		//		slice.Index(submatchIndex).Set(v)
	}
	return
}
Example #3
0
func (q *queryT) First() error {
	q.op = otQuery
	l := 1
	q.limit = &l

	rv := reflect.ValueOf(q.inst)
	rvi := reflect.Indirect(rv)

	if rvi.Kind() == reflect.Struct {
		dv := reflect.New(reflect.SliceOf(rvi.Type()))
		dv.Elem().Set(reflect.MakeSlice(reflect.SliceOf(rvi.Type()), 0, 1))

		if b, err := defaultClient.doRequest(q); err != nil {
			return err
		} else if err := handleResponse(b, dv.Interface()); err != nil {
			return err
		}

		dvi := reflect.Indirect(dv)
		if dvi.Len() > 0 {
			rv.Elem().Set(dv.Elem().Index(0))
		}
	} else if rvi.Kind() == reflect.Slice {
		if b, err := defaultClient.doRequest(q); err != nil {
			return err
		} else if err := handleResponse(b, q.inst); err != nil {
			return err
		}
	} else {
		return fmt.Errorf("expected struct or slice, got %s", rvi.Kind())
	}
	return nil
}
Example #4
0
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
}
Example #5
0
// loadSlice loads url and decodes it into a []elemType, returning the []elemType and error.
func loadSlice(url string, elemType interface{}) (interface{}, error) {
	t := reflect.TypeOf(elemType)
	result := reflect.New(reflect.SliceOf(t)).Elem() // result is []elemType

	link := url
	for link != "" {
		req, err := http.NewRequest("GET", link, nil)
		if err != nil {
			return result.Interface(), err
		}

		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			return result.Interface(), err
		}
		if resp.StatusCode > 299 {
			lr := io.LimitReader(resp.Body, 1024)
			bs, _ := ioutil.ReadAll(lr)
			resp.Body.Close()
			return result.Interface(), fmt.Errorf("http.Get: %v (%s)", resp.Status, bs)
		}

		tmp := reflect.New(reflect.SliceOf(t)) // tmp is *[]elemType
		err = json.NewDecoder(resp.Body).Decode(tmp.Interface())
		resp.Body.Close()
		if err != nil {
			return result.Interface(), err
		}

		result = reflect.AppendSlice(result, tmp.Elem())
		link = parseRel(resp.Header.Get("Link"), "next")
	}

	return result.Interface(), nil
}
Example #6
0
func (p Pages) GroupBy(key string, order ...string) (PagesGroup, error) {
	if len(p) < 1 {
		return nil, nil
	}

	direction := "asc"

	if len(order) > 0 && (strings.ToLower(order[0]) == "desc" || strings.ToLower(order[0]) == "rev" || strings.ToLower(order[0]) == "reverse") {
		direction = "desc"
	}

	ppt := reflect.TypeOf(&Page{})
	ft, ok := ppt.Elem().FieldByName(key)
	if !ok {
		return nil, errors.New("No such field in Page struct")
	}
	tmp := reflect.MakeMap(reflect.MapOf(ft.Type, reflect.SliceOf(ppt)))

	for _, e := range p {
		ppv := reflect.ValueOf(e)
		fv := ppv.Elem().FieldByName(key)
		if !tmp.MapIndex(fv).IsValid() {
			tmp.SetMapIndex(fv, reflect.MakeSlice(reflect.SliceOf(ppt), 0, 0))
		}
		tmp.SetMapIndex(fv, reflect.Append(tmp.MapIndex(fv), ppv))
	}

	var r []PageGroup
	for _, k := range sortKeys(tmp.MapKeys(), direction) {
		r = append(r, PageGroup{Key: k.Interface(), Pages: tmp.MapIndex(k).Interface().([]*Page)})
	}

	return r, nil
}
Example #7
0
func (p Pages) GroupBy(key, order string) ([]PageGroup, error) {
	if len(p) < 1 {
		return nil, nil
	}

	if order != "asc" && order != "desc" {
		return nil, errors.New("order argument must be 'asc' or 'desc'")
	}

	ppt := reflect.TypeOf(&Page{})
	ft, ok := ppt.Elem().FieldByName(key)
	if !ok {
		return nil, errors.New("No such field in Page struct")
	}
	tmp := reflect.MakeMap(reflect.MapOf(ft.Type, reflect.SliceOf(ppt)))

	for _, e := range p {
		ppv := reflect.ValueOf(e)
		fv := ppv.Elem().FieldByName(key)
		if !tmp.MapIndex(fv).IsValid() {
			tmp.SetMapIndex(fv, reflect.MakeSlice(reflect.SliceOf(ppt), 0, 0))
		}
		tmp.SetMapIndex(fv, reflect.Append(tmp.MapIndex(fv), ppv))
	}

	var r []PageGroup
	for _, k := range sortKeys(tmp.MapKeys(), order) {
		r = append(r, PageGroup{Key: k.Interface(), Data: tmp.MapIndex(k).Interface().([]*Page)})
	}

	return r, nil
}
Example #8
0
//return the next n permuations, if n>p.Left(),return all the left permuations
//if all permutaions generated or n is illegal(n<=0),return a empty slice
func (p *Permutator) NextN(n int) interface{} {
	<-p.idle
	//if n<=0 or we generate all pemutations,just return a empty slice
	if n <= 0 || p.left() == 0 {
		p.idle <- true
		return reflect.MakeSlice(reflect.SliceOf(p.value.Type()), 0, 0).Interface()
	}

	var i, j int
	cap := p.left()
	if cap > n {
		cap = n
	}

	result := reflect.MakeSlice(reflect.SliceOf(p.value.Type()), cap, cap)

	if p.length == 1 {
		p.index++
		l := reflect.MakeSlice(p.value.Type(), p.length, p.length)
		reflect.Copy(l, p.value)
		p.idle <- true
		result.Index(0).Set(l)
		return result.Interface()
	}

	if p.index == 1 {
		p.index++
		l := reflect.MakeSlice(p.value.Type(), p.length, p.length)
		reflect.Copy(l, p.value)
		result.Index(0).Set(l)
	}

	for k := 1; k < cap; k++ {
		for i = p.length - 2; i >= 0; i-- {
			if p.less(p.value.Index(i).Interface(), p.value.Index(i+1).Interface()) {
				break
			}
		}
		for j = p.length - 1; j >= 0; j-- {
			if p.less(p.value.Index(i).Interface(), p.value.Index(j).Interface()) {
				break
			}
		}
		//swap
		temp := reflect.ValueOf(p.value.Index(i).Interface())
		p.value.Index(i).Set(p.value.Index(j))
		p.value.Index(j).Set(temp)
		//reverse
		reverse(p.value, i+1, p.length-1)

		//increase the counter
		p.index++
		l := reflect.MakeSlice(p.value.Type(), p.length, p.length)
		reflect.Copy(l, p.value)
		result.Index(k).Set(l)
	}
	p.idle <- true
	return result.Interface()
}
Example #9
0
func newPool(size int, tp reflect.Type) *pool {
	return &pool{
		size: size,
		cur:  0,
		pool: reflect.MakeSlice(reflect.SliceOf(tp), size, size),
		tp:   reflect.SliceOf(tp),
	}
}
Example #10
0
func newPool(size int, tp reflect.Type) *pool {
	return &pool{
		size: size,
		cur:  0,
		pool: reflect.MakeSlice(reflect.SliceOf(tp), 0, 0), // init for don't allocate memory
		tp:   reflect.SliceOf(tp),
		stp:  tp,
	}
}
Example #11
0
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
}
Example #12
0
File: types.go Project: ajoulie/goa
// toReflectType converts the DataType to reflect.Type.
func toReflectType(dtype DataType) reflect.Type {
	switch dtype.Kind() {
	case BooleanKind:
		return reflect.TypeOf(true)
	case IntegerKind:
		return reflect.TypeOf(int(0))
	case NumberKind:
		return reflect.TypeOf(float64(0))
	case StringKind:
		return reflect.TypeOf("")
	case DateTimeKind:
		return reflect.TypeOf(time.Time{})
	case ObjectKind, UserTypeKind, MediaTypeKind:
		return reflect.TypeOf(map[string]interface{}{})
	case ArrayKind:
		return reflect.SliceOf(toReflectType(dtype.ToArray().ElemType.Type))
	case HashKind:
		hash := dtype.ToHash()
		// avoid complication: not allow object as the hash key
		var ktype reflect.Type
		if !hash.KeyType.Type.IsObject() {
			ktype = toReflectType(hash.KeyType.Type)
		} else {
			ktype = reflect.TypeOf([]interface{}{}).Elem()
		}
		return reflect.MapOf(ktype, toReflectType(hash.ElemType.Type))
	default:
		return reflect.TypeOf([]interface{}{}).Elem()
	}
}
Example #13
0
// SplitByEach splits a list into multiple lists. Each size of lists must be up to `each`
// e.g:
//   SplitByEach([]int{0,1,2,3,4}, 2)
//     -> [][]int{[]int{0,1}, []int{2, 3}, []int{4}}
func SplitByEach(list interface{}, eachSize int) interface{} {
	a := reflect.ValueOf(list)
	assertSlice(a)
	// create and allocate lists
	bucketType := a.Type()
	bucketListType := reflect.SliceOf(bucketType)
	tailSize := a.Len() % eachSize
	bucketListLen := a.Len()/eachSize + tailSize%2
	bucketList := reflect.MakeSlice(bucketListType, bucketListLen, bucketListLen)

	for i := 0; i < bucketListLen-1; i++ {
		bucket := bucketList.Index(i)
		bucket.Set(reflect.MakeSlice(bucketType, eachSize, eachSize))
		offset := i * eachSize
		for j := 0; j < eachSize; j++ {
			bucket.Index(j).Set(a.Index(offset + j))
		}
	}

	if tailSize == 0 {
		tailSize = eachSize
	}
	bucket := bucketList.Index(bucketListLen - 1)
	bucket.Set(reflect.MakeSlice(bucketType, tailSize, tailSize))
	offset := (bucketListLen - 1) * eachSize
	for j := 0; j < tailSize; j++ {
		bucket.Index(j).Set(a.Index(offset + j))
	}
	return bucketList.Interface()
}
Example #14
0
// GetAll fetches all items that we want to watch from the state.
func (b *allWatcherStateBacking) GetAll(all *multiwatcherStore) error {
	db, closer := b.st.newDB()
	defer closer()

	// TODO(rog) fetch collections concurrently?
	for _, c := range b.collectionByName {
		if c.subsidiary {
			continue
		}
		col, closer := db.GetCollection(c.name)
		defer closer()
		infoSlicePtr := reflect.New(reflect.SliceOf(c.infoType))
		if err := col.Find(nil).All(infoSlicePtr.Interface()); err != nil {
			return fmt.Errorf("cannot get all %s: %v", c.name, err)
		}
		infos := infoSlicePtr.Elem()
		for i := 0; i < infos.Len(); i++ {
			info := infos.Index(i).Addr().Interface().(backingEntityDoc)
			id := info.mongoId()
			err := info.updated(b.st, all, id)
			if err != nil {
				return errors.Annotatef(err, "failed to initialise backing for %s:%v", c.name, id)
			}
		}
	}
	return nil
}
Example #15
0
func (p *untypedParamBinder) setSliceFieldValue(target reflect.Value, defaultValue interface{}, data []string) error {
	if len(data) == 0 && p.parameter.Required && p.parameter.Default == nil {
		return errors.Required(p.Name, p.parameter.In)
	}
	defVal := reflect.Zero(target.Type())
	if defaultValue != nil {
		defVal = reflect.ValueOf(defaultValue)
	}
	if len(data) == 0 {
		target.Set(defVal)
		return nil
	}

	sz := len(data)
	value := reflect.MakeSlice(reflect.SliceOf(target.Type().Elem()), sz, sz)

	for i := 0; i < sz; i++ {
		if err := p.setFieldValue(value.Index(i), nil, data[i]); err != nil {
			return err
		}
	}

	target.Set(value)

	return nil
}
Example #16
0
func (m *GslMultiset) Slice_() interface{} {
	baseType := gogsl.GOGSL_SIZE_T_TYPE
	sliceType := reflect.SliceOf(baseType)
	size := K(m)
	hdr := &reflect.SliceHeader{Len: size, Cap: size, Data: uintptr(C.get_multiset_data((*C.gsl_multiset)(unsafe.Pointer(m.Ptr()))))}
	return reflect.NewAt(sliceType, unsafe.Pointer(hdr)).Elem().Interface()
}
Example #17
0
func (p *GslPermutation) Slice_() interface{} {
	baseType := gogsl.GOGSL_SIZE_T_TYPE
	sliceType := reflect.SliceOf(baseType)
	size := p.Len()
	hdr := &reflect.SliceHeader{Len: size, Cap: size, Data: uintptr(C.get_permutation_data((*C.gsl_permutation)(unsafe.Pointer(p.Ptr()))))}
	return reflect.NewAt(sliceType, unsafe.Pointer(hdr)).Elem().Interface()
}
Example #18
0
func goType(t *TypeInfo) reflect.Type {
	switch t.Type {
	case TypeVarchar, TypeAscii, TypeInet:
		return reflect.TypeOf(*new(string))
	case TypeBigInt, TypeCounter:
		return reflect.TypeOf(*new(int64))
	case TypeTimestamp:
		return reflect.TypeOf(*new(time.Time))
	case TypeBlob:
		return reflect.TypeOf(*new([]byte))
	case TypeBoolean:
		return reflect.TypeOf(*new(bool))
	case TypeFloat:
		return reflect.TypeOf(*new(float32))
	case TypeDouble:
		return reflect.TypeOf(*new(float64))
	case TypeInt:
		return reflect.TypeOf(*new(int))
	case TypeDecimal:
		return reflect.TypeOf(*new(*inf.Dec))
	case TypeUUID, TypeTimeUUID:
		return reflect.TypeOf(*new(UUID))
	case TypeList, TypeSet:
		return reflect.SliceOf(goType(t.Elem))
	case TypeMap:
		return reflect.MapOf(goType(t.Key), goType(t.Elem))
	case TypeVarint:
		return reflect.TypeOf(*new(*big.Int))
	default:
		return nil
	}
}
Example #19
0
func (db DBU) ListQuery(obj DBObject, extra string, args ...interface{}) (interface{}, error) {
	query := fmt.Sprintf("select %s from %s ", obj.SelectFields(), obj.TableName())
	if len(extra) > 0 {
		query += " " + extra
	}
	logger(query, args)
	val := reflect.ValueOf(obj)
	base := reflect.Indirect(val)
	t := reflect.TypeOf(base.Interface())
	results := reflect.Zero(reflect.SliceOf(t))
	rows, err := db.DB.Query(query, args...)
	if err != nil {
		log.Println("error on query: " + query + " -- " + err.Error())
		return nil, err
	}
	for rows.Next() {
		v := reflect.New(t)
		dest := v.Interface().(DBObject).MemberPointers()
		if err = rows.Scan(dest...); err != nil {
			fmt.Println("query:", query, "error:", err)
			continue
		}
		results = reflect.Append(results, v.Elem())
	}
	err = rows.Err()
	rows.Close()
	//fmt.Println("LIST LEN:", results.Len())
	return results.Interface(), err
}
Example #20
0
func (sl *sliceValue) Set(s string) error {
	sl.setted = true

	var tmpv interface{}

	if s == "" {
		tmpv = []interface{}{}
	} else {
		err := json.Unmarshal(([]byte)(s), &tmpv)
		if err != nil {
			return fmt.Errorf("In field %s, unmarshal slice error : %s", sl.field, err.Error())
		}
	}

	vm := reflect.ValueOf(tmpv)

	tshould := sl.typ

	le := vm.Len()
	tmpTransed := reflect.MakeSlice(reflect.SliceOf(tshould), le, le)

	for i := 0; i < le; i++ {
		if reflect.TypeOf(vm.Index(i).Interface()).ConvertibleTo(tshould) {
			tmpTransed.Index(i).Set(reflect.ValueOf(vm.Index(i).Interface()).Convert(tshould))
		} else {
			return fmt.Errorf("In field %s, have a Un Convertible value, at postion %d", sl.field, i)
		}
	}

	sl.Vals = tmpTransed

	return nil
}
Example #21
0
// readAllStateCommon reads and unmarshals (given a function) all state into a
// list of core.State objects.
// XXX: move this to some common file
func readAllStateCommon(d core.StateDriver, baseKey string, sType core.State,
	unmarshal func([]byte, interface{}) error) ([]core.State, error) {
	stateType := reflect.TypeOf(sType)
	sliceType := reflect.SliceOf(stateType)
	values := reflect.MakeSlice(sliceType, 0, 1)

	byteValues, err := d.ReadAll(baseKey)
	if err != nil {
		return nil, err
	}
	for _, byteValue := range byteValues {
		value := reflect.New(stateType)
		err = unmarshal(byteValue, value.Interface())
		if err != nil {
			return nil, err
		}
		values = reflect.Append(values, value.Elem())
	}

	stateValues := []core.State{}
	for i := 0; i < values.Len(); i++ {
		// sanity checks
		if !values.Index(i).Elem().FieldByName("CommonState").IsValid() {
			return nil, core.Errorf("The state structure %v is missing core.CommonState",
				stateType)
		}
		//the following works as every core.State is expected to embed core.CommonState struct
		values.Index(i).Elem().FieldByName("CommonState").FieldByName("StateDriver").Set(reflect.ValueOf(d))
		stateValue := values.Index(i).Interface().(core.State)
		stateValues = append(stateValues, stateValue)
	}
	return stateValues, nil
}
Example #22
0
func (f *FutureSQL) RunQuery(pf *ExecutableFuture, req *FutureRequest, parameters []SQLExpression) ([]*Record, bool, *OError) {
	lp, psql := f.Resource.GetPromise(pf.Request)
	defer lp.Release()

	tx, err := psql.GetSQLTransaction(f.Resource.DB)
	if err != nil {
		oe := ErrorToOError(err)
		return []*Record{}, false, &oe
	}
	vs := reflect.New(reflect.SliceOf(reflect.PtrTo(f.Resource.Type))).Interface()
	query, queryargs, is_single := f.PrepareQuery(parameters...)
	pf.Request.API.Logger.Debugf("RUN QUERY: %#v %#v\n", query, queryargs)
	err = meddler.QueryAll(
		tx,
		vs,
		query,
		queryargs...,
	)
	var oerr *OError
	if err != nil {
		oerr = &OError{
			Title:  err.Error(),
			Detail: fmt.Sprintf("%s -- %#v\n", query, queryargs),
		}
	}
	return ConvertInterfaceSliceToRecordSlice(vs), is_single, oerr
}
Example #23
0
// 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
}
Example #24
0
func setArray(fv reflect.Value, v *ast.Array) error {
	if len(v.Value) == 0 {
		return nil
	}
	typ := reflect.TypeOf(v.Value[0])
	for _, vv := range v.Value[1:] {
		if typ != reflect.TypeOf(vv) {
			return fmt.Errorf("array cannot contain multiple types")
		}
	}
	sliceType := fv.Type()
	if fv.Kind() == reflect.Interface {
		sliceType = reflect.SliceOf(sliceType)
	}
	slice := reflect.MakeSlice(sliceType, 0, len(v.Value))
	t := sliceType.Elem()
	for _, vv := range v.Value {
		tmp := reflect.New(t).Elem()
		if err := setValue(tmp, vv); err != nil {
			return err
		}
		slice = reflect.Append(slice, tmp)
	}
	fv.Set(slice)
	return nil
}
Example #25
0
func (c *ConditionContains) CheckCondition(game *Game, action *Action) bool {
	container := InstantiateFilterSourcePrototype(game, action, c.container, true)
	element := InstantiateFilterSourcePrototype(game, action, c.element, true)
	if reflect.SliceOf(reflect.TypeOf(element)) != reflect.TypeOf(container) {
		return false
	}
	switch element.(type) {
	case TraitType:
		trait := element.(TraitType)
		traits := container.([]TraitType)
		for _, t := range traits {
			if t == trait {
				return true
			}
		}
	case *Property:
		property := element.(*Property)
		properties := container.([]*Property)
		for _, p := range properties {
			if p.equals(property) {
				return true
			}
		}
	}
	return false
}
Example #26
0
func CopyExact(dest interface{}, src interface{}) {
	dV := reflect.ValueOf(dest)
	sV := reflect.ValueOf(src)
	if dV.Kind() == reflect.Ptr {
		dV = dV.Elem()
	}
	if dV.Kind() == reflect.Array && !dV.CanAddr() {
		panic(fmt.Sprintf("dest not addressable: %T", dest))
	}
	if sV.Kind() == reflect.Ptr {
		sV = sV.Elem()
	}
	if sV.Kind() == reflect.String {
		sV = sV.Convert(reflect.SliceOf(dV.Type().Elem()))
	}
	if !sV.IsValid() {
		panic("invalid source, probably nil")
	}
	if dV.Len() != sV.Len() {
		panic(fmt.Sprintf("dest len (%d) != src len (%d)", dV.Len(), sV.Len()))
	}
	if dV.Len() != reflect.Copy(dV, sV) {
		panic("dammit")
	}
}
Example #27
0
// Implements storage.Interface.
func (c *Cacher) List(ctx context.Context, key string, resourceVersion string, pred SelectionPredicate, listObj runtime.Object) error {
	if resourceVersion == "" {
		// If resourceVersion is not specified, serve it from underlying
		// storage (for backward compatibility).
		return c.storage.List(ctx, key, resourceVersion, pred, listObj)
	}

	// If resourceVersion is specified, serve it from cache.
	// It's guaranteed that the returned value is at least that
	// fresh as the given resourceVersion.
	listRV, err := ParseListResourceVersion(resourceVersion)
	if err != nil {
		return err
	}

	trace := util.NewTrace(fmt.Sprintf("cacher %v: List", c.objectType.String()))
	defer trace.LogIfLong(500 * time.Millisecond)

	c.ready.wait()
	trace.Step("Ready")

	// List elements with at least 'listRV' from cache.
	listPtr, err := meta.GetItemsPtr(listObj)
	if err != nil {
		return err
	}
	listVal, err := conversion.EnforcePtr(listPtr)
	if err != nil || listVal.Kind() != reflect.Slice {
		return fmt.Errorf("need a pointer to slice, got %v", listVal.Kind())
	}
	filter := filterFunction(key, pred)

	objs, readResourceVersion, err := c.watchCache.WaitUntilFreshAndList(listRV, trace)
	if err != nil {
		return fmt.Errorf("failed to wait for fresh list: %v", err)
	}
	trace.Step(fmt.Sprintf("Listed %d items from cache", len(objs)))
	if len(objs) > listVal.Cap() && pred.Label.Empty() && pred.Field.Empty() {
		// Resize the slice appropriately, since we already know that none
		// of the elements will be filtered out.
		listVal.Set(reflect.MakeSlice(reflect.SliceOf(c.objectType.Elem()), 0, len(objs)))
		trace.Step("Resized result")
	}
	for _, obj := range objs {
		elem, ok := obj.(*storeElement)
		if !ok {
			return fmt.Errorf("non *storeElement returned from storage: %v", obj)
		}
		if filter(elem.Key, elem.Object) {
			listVal.Set(reflect.Append(listVal, reflect.ValueOf(elem.Object).Elem()))
		}
	}
	trace.Step(fmt.Sprintf("Filtered %d items", listVal.Len()))
	if c.versioner != nil {
		if err := c.versioner.UpdateList(listObj, readResourceVersion); err != nil {
			return err
		}
	}
	return nil
}
Example #28
0
// NewSlice initialize a slice of struct for the Resource
func (res *Resource) NewSlice() interface{} {
	sliceType := reflect.SliceOf(reflect.TypeOf(res.Value))
	slice := reflect.MakeSlice(sliceType, 0, 0)
	slicePtr := reflect.New(sliceType)
	slicePtr.Elem().Set(slice)
	return slicePtr.Interface()
}
Example #29
0
func (db DBU) ObjectListQuery(Kind interface{}, extra string, args ...interface{}) (interface{}, error) {
	Query := createQuery(Kind, false)
	if len(extra) > 0 {
		Query += " " + extra
	}
	if debugging() {
		fmt.Fprintln(os.Stderr, "Q:", Query, "A:", args)
	}
	t := reflect.TypeOf(Kind)
	results := reflect.Zero(reflect.SliceOf(t))
	rows, err := db.DB.Query(Query, args...)
	if err != nil {
		log.Println("error on Query: " + Query + " -- " + err.Error())
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		v := reflect.New(t)
		dest := sPtrs(v.Interface())
		err = rows.Scan(dest...)
		if err != nil {
			log.Println("scan error: " + err.Error())
			log.Println("scan query: "+Query+" args:", args)
			return nil, err
		}
		results = reflect.Append(results, v.Elem())
	}
	return results.Interface(), nil
}
Example #30
0
func (p *untypedParamBinder) setSliceFieldValue(target reflect.Value, defaultValue interface{}, data []string, hasKey bool) error {
	sz := len(data)
	if (!hasKey || (!p.parameter.AllowEmptyValue && (sz == 0 || (sz == 1 && data[0] == "")))) && p.parameter.Required && defaultValue == nil {
		return errors.Required(p.Name, p.parameter.In)
	}

	defVal := reflect.Zero(target.Type())
	if defaultValue != nil {
		defVal = reflect.ValueOf(defaultValue)
	}

	if !target.CanSet() {
		return nil
	}
	if sz == 0 {
		target.Set(defVal)
		return nil
	}

	value := reflect.MakeSlice(reflect.SliceOf(target.Type().Elem()), sz, sz)

	for i := 0; i < sz; i++ {
		if err := p.setFieldValue(value.Index(i), nil, data[i], hasKey); err != nil {
			return err
		}
	}

	target.Set(value)

	return nil
}