Esempio n. 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()
}
Esempio n. 2
0
func (d *Decoder) decodeSlice(s *decodStatus, v reflect.Value, t reflect.Type, tg tag) error {
	if _, isInline := tg.Modifiers["inline"]; isInline {
		val, ok := s.GetValue(d.env)
		if !ok {
			return nil
		}
		elements := d.arrSep.Split(val, -1)
		slice := reflect.MakeSlice(t, 0, len(elements))
		for _, s := range elements {
			mv := reflect.New(t.Elem())
			err := d.decodeField(mv.Elem(), s)
			if err != nil {
				return err
			}
			slice = reflect.Append(slice, mv.Elem())
		}
		v.Set(slice)
		return nil
	}
	index := s.GetIndex()
	slice := reflect.MakeSlice(t, 0, len(index))
	for _, i := range index {
		mv := reflect.New(t.Elem())
		err := d.decodeElement(s, mv.Elem(), mv.Elem().Type(), tag{Name: strconv.Itoa(i), Modifiers: tg.Modifiers})
		if err != nil {
			return err
		}
		slice = reflect.Append(slice, mv.Elem())
	}
	v.Set(slice)
	return nil
}
Esempio n. 3
0
func TestRequiredValidation(t *testing.T) {
	strParam := spec.QueryParam("name").Typed("string", "").AsRequired()
	validateRequiredTest(t, strParam, reflect.ValueOf(""))
	validateRequiredAllowEmptyTest(t, strParam, reflect.ValueOf(""))

	intParam := spec.QueryParam("id").Typed("integer", "int32").AsRequired()
	validateRequiredTest(t, intParam, reflect.ValueOf(int32(0)))
	validateRequiredAllowEmptyTest(t, intParam, reflect.ValueOf(int32(0)))
	longParam := spec.QueryParam("id").Typed("integer", "int64").AsRequired()
	validateRequiredTest(t, longParam, reflect.ValueOf(int64(0)))
	validateRequiredAllowEmptyTest(t, longParam, reflect.ValueOf(int64(0)))

	floatParam := spec.QueryParam("score").Typed("number", "float").AsRequired()
	validateRequiredTest(t, floatParam, reflect.ValueOf(float32(0)))
	validateRequiredAllowEmptyTest(t, floatParam, reflect.ValueOf(float32(0)))
	doubleParam := spec.QueryParam("score").Typed("number", "double").AsRequired()
	validateRequiredTest(t, doubleParam, reflect.ValueOf(float64(0)))
	validateRequiredAllowEmptyTest(t, doubleParam, reflect.ValueOf(float64(0)))

	dateTimeParam := spec.QueryParam("registered").Typed("string", "date-time").AsRequired()
	validateRequiredTest(t, dateTimeParam, reflect.ValueOf(strfmt.DateTime{}))
	// validateRequiredAllowEmptyTest(t, dateTimeParam, reflect.ValueOf(strfmt.DateTime{}))

	dateParam := spec.QueryParam("registered").Typed("string", "date").AsRequired()
	validateRequiredTest(t, dateParam, reflect.ValueOf(strfmt.Date{}))
	// validateRequiredAllowEmptyTest(t, dateParam, reflect.ValueOf(strfmt.DateTime{}))

	sliceParam := spec.QueryParam("tags").CollectionOf(stringItems, "").AsRequired()
	validateRequiredTest(t, sliceParam, reflect.MakeSlice(reflect.TypeOf([]string{}), 0, 0))
	validateRequiredAllowEmptyTest(t, sliceParam, reflect.MakeSlice(reflect.TypeOf([]string{}), 0, 0))
}
Esempio n. 4
0
// 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]))
		}
	}
}
Esempio n. 5
0
func convertSlice(in interface{}, val reflect.Value) *ConfigError {
	if iary, ok := in.([]interface{}); !ok {
		return &ConfigError{ErrInvalidType, ""}
	} else if len(iary) > 0 {
		var convertor ConvertFunc

		ele := reflect.MakeSlice(val.Type(), 1, 1).Index(0)
		convertor = convertFuncs.get(ele)
		if convertor == nil {
			return &ConfigError{ErrInvalidType, ""}
		}

		ary := reflect.MakeSlice(val.Type(), len(iary), len(iary))
		for i, ele := range iary {
			if err := convertor(ele, ary.Index(i)); err != nil {
				if len(err.Field) > 0 {
					err.Field = fmt.Sprintf("[%d].%s", i, err.Field)
				} else {
					err.Field = fmt.Sprintf("[%d]", i)
				}
				return err
			}
		}
		val.Set(ary)
	}
	return nil
}
Esempio n. 6
0
// Adds item to a slice.
func addSliceItem(elem *reflect.Value, section, key, value string) (err error) {
	//fmt.Printf("\tADD SLICE ITEM: [%s] %s %s\n", section, key, value)

	section = toFieldName(section)
	key = toFieldName(key)

	field, err := findField(elem, section, key)
	if err != nil {
		return err
	}

	if err = isFieldModifiable(field, key, reflect.Slice); err != nil {
		return
	}

	// First on consecutive add ?
	if field.IsNil() {
		// First add
		field.Set(reflect.MakeSlice(field.Type(), 1, 1))
		field.Index(0).Set( //reflect.ValueOf(value))
			reflect.ValueOf(value).Convert(field.Type().Elem()))
	} else {
		// Consecutive adds copy slice and increase its size by 1
		l := field.Len()
		fieldNew := reflect.MakeSlice(field.Type(), l+1, l+1)
		for i := 0; i < l; i++ {
			fieldNew.Index(i).Set(field.Index(i))
		}
		fieldNew.Index(l).Set(
			reflect.ValueOf(value).Convert(field.Type().Elem()))
		field.Set(fieldNew)
	}

	return
}
Esempio n. 7
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()
}
Esempio n. 8
0
// DecoderContainer supports common cases for decoding into a nil
// interface{} depending on the context.
//
// When decoding into a nil interface{}, the following rules apply as we have
// to make assumptions about the specific types you want.
//    - Maps are decoded as map[interface{}]interface{}
//      unless you provide a default map type when creating your decoder.
//      option: MapType
//    - Lists are always decoded as []interface{}
//      unless you provide a default slice type when creating your decoder.
//      option: SliceType
//    - raw bytes are decoded into []byte or string depending on setting of:
//      option: BytesStringMapValue     (if within a map value, use this setting)
//      option: BytesStringSliceElement (else if within a slice, use this setting)
//      option: BytesStringLiteral      (else use this setting)
func (d SimpleDecoderContainerResolver) DecoderContainer(
	parentcontainer reflect.Value, parentkey interface{},
	length int, ct ContainerType) (rvn reflect.Value) {
	switch ct {
	case ContainerMap:
		if d.MapType != nil {
			rvn = reflect.MakeMap(d.MapType)
		} else {
			rvn = reflect.MakeMap(mapIntfIntfTyp)
		}
	case ContainerList:
		if d.SliceType != nil {
			rvn = reflect.MakeSlice(d.SliceType, length, length)
		} else {
			rvn = reflect.MakeSlice(intfSliceTyp, length, length)
		}
	case ContainerRawBytes:
		rk := parentcontainer.Kind()
		if (rk == reflect.Invalid && d.BytesStringLiteral) ||
			(rk == reflect.Slice && d.BytesStringSliceElement) ||
			(rk == reflect.Map && d.BytesStringMapValue) {
			rvm := ""
			rvn = reflect.ValueOf(&rvm)
		} else {
			rvn = reflect.MakeSlice(byteSliceTyp, length, length)
		}
	}
	// fmt.Printf("DecoderContainer: %T, %v\n", rvn.Interface(), rvn.Interface())
	return
}
Esempio n. 9
0
func (this *SpecificDatumReader) mapArray(field Schema, reflectField reflect.Value, dec Decoder) (reflect.Value, error) {
	if arrayLength, err := dec.ReadArrayStart(); err != nil {
		return reflect.ValueOf(arrayLength), err
	} else {
		array := reflect.MakeSlice(reflectField.Type(), 0, 0)
		for {
			arrayPart := reflect.MakeSlice(reflectField.Type(), int(arrayLength), int(arrayLength))
			var i int64 = 0
			for ; i < arrayLength; i++ {
				val, err := this.readValue(field.(*ArraySchema).Items, arrayPart.Index(int(i)), dec)
				if err != nil {
					return reflect.ValueOf(arrayLength), err
				}
				if val.Kind() == reflect.Ptr {
					arrayPart.Index(int(i)).Set(val.Elem())
				} else {
					arrayPart.Index(int(i)).Set(val)
				}
			}
			//concatenate arrays
			concatArray := reflect.MakeSlice(reflectField.Type(), array.Len()+int(arrayLength), array.Cap()+int(arrayLength))
			reflect.Copy(concatArray, array)
			reflect.Copy(concatArray, arrayPart)
			array = concatArray
			arrayLength, err = dec.ArrayNext()
			if err != nil {
				return reflect.ValueOf(arrayLength), err
			} else if arrayLength == 0 {
				break
			}
		}
		return array, nil
	}
}
Esempio n. 10
0
func _partition(values []reflect.Value) []reflect.Value {
	slice := interfaceToValue(values[0])
	fn := values[1]

	var t, f reflect.Value

	if values[0].Kind() == reflect.Interface {
		t = reflect.ValueOf(make([]interface{}, 0))
		f = reflect.ValueOf(make([]interface{}, 0))
	} else {
		t = reflect.MakeSlice(slice.Type(), 0, 0)
		f = reflect.MakeSlice(slice.Type(), 0, 0)
	}

	for i := 0; i < slice.Len(); i++ {
		e := slice.Index(i)
		r := fn.Call([]reflect.Value{e})
		if r[0].Bool() {
			t = reflect.Append(t, e)
		} else {
			f = reflect.Append(f, e)
		}
	}
	return []reflect.Value{t, f}
}
Esempio n. 11
0
func (f *decFnInfo) kSlice(rv reflect.Value) {
	// A slice can be set from a map or array in stream.
	currEncodedType := f.dd.currentEncodedType()

	switch currEncodedType {
	case valueTypeBytes, valueTypeString:
		if f.ti.rtid == uint8SliceTypId || f.ti.rt.Elem().Kind() == reflect.Uint8 {
			if bs2, changed2 := f.dd.decodeBytes(rv.Bytes()); changed2 {
				rv.SetBytes(bs2)
			}
			return
		}
	}

	if shortCircuitReflectToFastPath && rv.CanAddr() {
		switch f.ti.rtid {
		case intfSliceTypId:
			f.d.decSliceIntf(rv.Addr().Interface().(*[]interface{}), currEncodedType, f.array)
			return
		case uint64SliceTypId:
			f.d.decSliceUint64(rv.Addr().Interface().(*[]uint64), currEncodedType, f.array)
			return
		case int64SliceTypId:
			f.d.decSliceInt64(rv.Addr().Interface().(*[]int64), currEncodedType, f.array)
			return
		case strSliceTypId:
			f.d.decSliceStr(rv.Addr().Interface().(*[]string), currEncodedType, f.array)
			return
		}
	}

	containerLen, containerLenS := decContLens(f.dd, currEncodedType)

	// an array can never return a nil slice. so no need to check f.array here.

	if rv.IsNil() {
		rv.Set(reflect.MakeSlice(f.ti.rt, containerLenS, containerLenS))
	}

	if containerLen == 0 {
		return
	}

	if rvcap, rvlen := rv.Len(), rv.Cap(); containerLenS > rvcap {
		if f.array { // !rv.CanSet()
			decErr(msgDecCannotExpandArr, rvcap, containerLenS)
		}
		rvn := reflect.MakeSlice(f.ti.rt, containerLenS, containerLenS)
		if rvlen > 0 {
			reflect.Copy(rvn, rv)
		}
		rv.Set(rvn)
	} else if containerLenS > rvlen {
		rv.SetLen(containerLenS)
	}

	for j := 0; j < containerLenS; j++ {
		f.d.decodeValue(rv.Index(j))
	}
}
Esempio n. 12
0
func GetSliceConvert(c *Convertors) func(*Params, string, reflect.Type) reflect.Value {
	return func(p *Params, name string, typ reflect.Type) reflect.Value {
		var values ItemByIndex
		var maxIdx = 0
		var noindex = 0
		processItem := func(key string, vals []string) {
			var idx int
			var err error
			if !strings.HasPrefix(key, name+"[") {
				return
			}

			lIdx, rIdx := len(name), strings.IndexByte(key[len(name):], ']')+len(name)
			if rIdx == -1 {
				//not have ] char in key
				return
			}
			//process e.g. name[]
			if lIdx == rIdx-1 {
				noindex++
				goto END
			}

			idx, err = strconv.Atoi(key[lIdx+1 : rIdx])
			if err != nil {
				return
			}
			if idx > maxIdx {
				maxIdx = idx
			}
		END:
			value := c.Convert(p, key[:rIdx+1], typ.Elem())
			values = append(values, &item{idx, value})

		}
		for k, vals := range p.Values {
			processItem(k, vals)
		}
		//if array len small than 10000, keep index
		if maxIdx < 10000 {
			slice := reflect.MakeSlice(typ, maxIdx+1, maxIdx+noindex+1)
			for _, val := range values {
				if val.index > -1 {
					slice.Index(val.index).Set(val.value)
				} else {
					slice = reflect.Append(slice, val.value)
				}
			}
			return slice
		}

		sort.Sort(values)
		slice := reflect.MakeSlice(typ, 0, len(values))
		for _, val := range values {
			slice = reflect.Append(slice, val.value)
		}
		return slice
	}
}
Esempio n. 13
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()
}
Esempio n. 14
0
// MakeSlice creates a new, empty slice value for the given type. The
// parameter is expected to be an exemplar of the slice type to make.
func MakeSlice(i interface{}) reflect.Value {
	ut := Indirect(i).Type()
	if ut.Kind() == reflect.Slice {
		return reflect.MakeSlice(ut, 0, 0)
	}
	st := reflect.SliceOf(ut)
	return reflect.MakeSlice(st, 0, 0)
}
Esempio n. 15
0
//FIXME: fix when v is invalid
// type(1) | name length(1) | item size(4) | raw name bytes | 0x00
// | element number(4) | element1 | ... | elementN
func (d *decodeState) array(v reflect.Value) {
	d.off += 1 // type

	klen := int(Int8(d.data[d.off:]))
	d.off += 1 // name length

	// vlen := int(Int32(d.data[d.off:]))
	d.off += 4 //  content length

	//var key string
	if klen > 0 {
		key := d.data[d.off : d.off+klen-1]
		d.off += klen
		v = fieldByTag(v, key)
		u, pv := d.indirect(v, false)
		if u != nil {
			d.off -= 1 + 1 + 4 + klen
			if err := u.UnmarshalMCPACK(d.next()); err != nil {
				d.error(err)
			}
			return
		}
		v = pv
	}

	n := int(Int32(d.data[d.off:]))
	d.off += 4 // member number

	if v.Kind() == reflect.Slice {
		if n > v.Cap() {
			newv := reflect.MakeSlice(v.Type(), n, n)
			v.Set(newv)
		}
		v.SetLen(n)
	}

	for i := 0; i < n; i++ {
		if i < v.Len() {
			d.value(v.Index(i))
		} else {
			d.value(reflect.Value{})
		}
	}

	if n < v.Len() {
		if v.Kind() == reflect.Array {
			z := reflect.Zero(v.Type().Elem())
			for i := 0; i < v.Len(); i++ {
				v.Index(i).Set(z)
			}
		}
	}

	if n == 0 && v.Kind() == reflect.Slice {
		v.Set(reflect.MakeSlice(v.Type(), 0, 0))
	}
}
Esempio n. 16
0
// unmarshal for when rv's Kind is Slice
func unmarshalSlice(av *dynamodb.AttributeValue, rv reflect.Value) error {
	switch {
	case av.B != nil:
		rv.SetBytes(av.B)
		return nil

	case av.L != nil:
		slicev := reflect.MakeSlice(rv.Type(), 0, len(av.L))
		for _, innerAV := range av.L {
			innerRV := reflect.New(rv.Type().Elem()).Elem()
			if err := unmarshalReflect(innerAV, innerRV); err != nil {
				return err
			}
			slicev = reflect.Append(slicev, innerRV)
		}
		rv.Set(slicev)
		return nil

	// there's probably a better way to do these
	case av.BS != nil:
		slicev := reflect.MakeSlice(rv.Type(), 0, len(av.L))
		for _, b := range av.BS {
			innerRV := reflect.New(rv.Type().Elem()).Elem()
			if err := unmarshalReflect(&dynamodb.AttributeValue{B: b}, innerRV); err != nil {
				return err
			}
			slicev = reflect.Append(slicev, innerRV)
		}
		rv.Set(slicev)
		return nil
	case av.SS != nil:
		slicev := reflect.MakeSlice(rv.Type(), 0, len(av.L))
		for _, str := range av.SS {
			innerRV := reflect.New(rv.Type().Elem()).Elem()
			if err := unmarshalReflect(&dynamodb.AttributeValue{S: str}, innerRV); err != nil {
				return err
			}
			slicev = reflect.Append(slicev, innerRV)
		}
		rv.Set(slicev)
		return nil
	case av.NS != nil:
		slicev := reflect.MakeSlice(rv.Type(), 0, len(av.L))
		for _, n := range av.NS {
			innerRV := reflect.New(rv.Type().Elem()).Elem()
			if err := unmarshalReflect(&dynamodb.AttributeValue{N: n}, innerRV); err != nil {
				return err
			}
			slicev = reflect.Append(slicev, innerRV)
		}
		rv.Set(slicev)
		return nil
	}
	return errors.New("dynamo: unmarshal slice: B, L, BS, SS, NS are nil")
}
Esempio n. 17
0
// subtractRepeatedMessage subtracts protos in list2 from the corresponding protos in list1.
// The input lists should only contain protos, and the protos should have their identifiers
// be their first field.
func subtractRepeatedMessage(list1, list2 interface{}) reflect.Value {
	if list1 == nil && list2 == nil {
		return reflect.ValueOf([]proto.Message{})
	}
	l1 := genericListOrDie(list1)
	if list2 == nil {
		return l1
	}
	l2 := genericListOrDie(list2)
	if list1 == nil {
		// Need to make negatives of the elements in list2, so can't just return here.
		l1 = reflect.MakeSlice(l2.Type(), 0, 0)
	}

	t1, t2 := l1.Type(), l2.Type()
	if t1 != t2 {
		log.Fatalf("Mismatched list types: %v vs %v", t1, t2)
	}

	// All entries may not occur in both files, so use maps to keep track of everything.
	m1, m2 := make(map[string]proto.Message), make(map[string]proto.Message)
	for i := 0; i < l1.Len(); i++ {
		item := l1.Index(i)
		m1[name(item)] = item.Interface().(proto.Message)
	}
	for i := 0; i < l2.Len(); i++ {
		item := l2.Index(i)
		m2[name(item)] = item.Interface().(proto.Message)
	}

	out := reflect.MakeSlice(t1, 0, l1.Len()+l2.Len())
	for n, p1 := range m1 {
		p2, ok := m2[n]
		if !ok {
			// In list1 but not list2.
			out = reflect.Append(out, reflect.ValueOf(proto.Clone(p1)))
			continue
		}
		if diff := subtractMessage(p1, p2); diff != nil {
			out = reflect.Append(out, reflect.ValueOf(diff))
		}
	}
	for n, p2 := range m2 {
		if _, ok := m1[n]; !ok {
			// In list2 but not list1. Subtract to get negative values.
			if diff := subtractMessage(nil, p2); diff != nil {
				out = reflect.Append(out, reflect.ValueOf(diff))
			}
		}
	}
	if out.Len() == 0 {
		return reflect.Zero(l1.Type())
	}
	return out
}
Esempio n. 18
0
func makePartitions(col reflect.Value, kind reflect.Kind) (reflect.Value, reflect.Value) {
	var t, f reflect.Value

	if kind == reflect.Interface {
		t = reflect.ValueOf(make([]interface{}, 0))
		f = reflect.ValueOf(make([]interface{}, 0))
	} else {
		t = reflect.MakeSlice(col.Type(), 0, 0)
		f = reflect.MakeSlice(col.Type(), 0, 0)
	}
	return t, f
}
Esempio n. 19
0
func collectSlice(s reflect.Value, f interface{}) (r interface{}, ok bool) {
	end := s.Len()
	switch f := f.(type) {
	case func(interface{}) interface{}:
		c := reflect.MakeSlice(s.Type(), end, end)
		for i := 0; i < end; i++ {
			c.Index(i).Set(reflect.ValueOf(f(s.Index(i).Interface())))
		}
		r = c.Interface()
		ok = true

	case func(int, interface{}) interface{}:
		c := reflect.MakeSlice(s.Type(), end, end)
		for i := 0; i < end; i++ {
			c.Index(i).Set(reflect.ValueOf(f(i, s.Index(i).Interface())))
		}
		r = c.Interface()
		ok = true

	case func(interface{}, interface{}) interface{}:
		c := reflect.MakeSlice(s.Type(), end, end)
		for i := 0; i < end; i++ {
			c.Index(i).Set(reflect.ValueOf(f(i, s.Index(i).Interface())))
		}
		r = c.Interface()
		ok = true

	default:
		if f := reflect.ValueOf(f); f.Kind() == reflect.Func {
			end := s.Len()
			c := reflect.MakeSlice(s.Type(), end, end)
			switch f.Type().NumIn() {
			case 1:
				for i := 0; i < end; i++ {
					c.Index(i).Set(f.Call([]reflect.Value{s.Index(i)})[0])
				}
				ok = true

			case 2:
				for i := 0; i < end; i++ {
					c.Index(i).Set(f.Call([]reflect.Value{reflect.ValueOf(i), s.Index(i)})[0])
				}
				ok = true
			}
			if ok {
				r = c.Interface()
			}
		}
	}
	return
}
Esempio n. 20
0
// Captures the specified array lists and returns them as a single 2d array.
// After capturing the values the source lists are reset to new empty arrays.
func (self *Config) captureLists(lists ...interface{}) []interface{} {
	captures := make([]interface{}, len(lists))
	for index, list := range lists {
		sliceType := reflect.SliceOf(reflect.TypeOf(list).Elem().Elem())
		listValue := reflect.ValueOf(list).Elem()
		len := listValue.Len()

		captures[index] = reflect.MakeSlice(sliceType, len, len).Interface()
		reflect.Copy(reflect.ValueOf(captures[index]), listValue)
		listValue.Set(reflect.ValueOf(reflect.MakeSlice(sliceType, 0, 0).Interface()))
	}

	return captures
}
Esempio n. 21
0
func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error {
	dataVal := reflect.Indirect(reflect.ValueOf(data))
	dataValKind := dataVal.Kind()
	valType := val.Type()
	valElemType := valType.Elem()
	sliceType := reflect.SliceOf(valElemType)

	valSlice := val
	if valSlice.IsNil() || d.config.ZeroFields {

		// Check input type
		if dataValKind != reflect.Array && dataValKind != reflect.Slice {
			// Accept empty map instead of array/slice in weakly typed mode
			if d.config.WeaklyTypedInput && dataVal.Kind() == reflect.Map && dataVal.Len() == 0 {
				val.Set(reflect.MakeSlice(sliceType, 0, 0))
				return nil
			} else {
				return fmt.Errorf(
					"'%s': source data must be an array or slice, got %s", name, dataValKind)
			}
		}

		// Make a new slice to hold our result, same size as the original data.
		valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len())
	}

	// Accumulate any errors
	errors := make([]string, 0)

	for i := 0; i < dataVal.Len(); i++ {
		currentData := dataVal.Index(i).Interface()
		currentField := valSlice.Index(i)

		fieldName := fmt.Sprintf("%s[%d]", name, i)
		if err := d.decode(fieldName, currentData, currentField); err != nil {
			errors = appendErrors(errors, err)
		}
	}

	// Finally, set the value to the slice we built up
	val.Set(valSlice)

	// If there were errors, we return those
	if len(errors) > 0 {
		return &Error{errors}
	}

	return nil
}
Esempio n. 22
0
func Subslice(container interface{}, start, end int) (r interface{}) {
	if start < 0 {
		start = 0
	}
	switch container := container.(type) {
	case Sliceable:
		r = container.Subslice(start, end)

	case Indexable:
		LastIndex := container.Len() - 1
		if end > LastIndex {
			end = LastIndex
		}
		l := end - start
		if c, ok := container.(Typed); ok {
			s := reflect.MakeSlice(c.Type(), l, l)
			for i, j := 0, start; j < end; j++ {
				s.Index(i).Set(reflect.ValueOf(container.At(j)))
				i++
			}
			r = s.Interface()
		} else {
			s := make([]interface{}, l, l)
			for i, j := 0, start; j < end; j++ {
				s[i] = container.At(j)
				i++
			}
			r = s
		}

	default:
		switch container := reflect.ValueOf(container); container.Kind() {
		case reflect.Slice:
			LastIndex := container.Len() - 1
			if end > LastIndex {
				end = LastIndex
			}
			l := end - start
			s := reflect.MakeSlice(container.Type(), l, l)
			for i, j := 0, start; j < end; j++ {
				s.Index(i).Set(container.Index(j))
				i++
			}
			r = s.Interface()
		}
	}
	return
}
Esempio n. 23
0
func (f *decFnInfo) kSlice(rv reflect.Value) {
	// A slice can be set from a map or array in stream.
	currEncodedType := f.dd.currentEncodedType()

	switch currEncodedType {
	case valueTypeBytes, valueTypeString:
		if f.ti.rtid == uint8SliceTypId || f.ti.rt.Elem().Kind() == reflect.Uint8 {
			if bs2, changed2 := f.dd.decodeBytes(rv.Bytes()); changed2 {
				rv.SetBytes(bs2)
			}
			return
		}
	}

	containerLen, containerLenS := decContLens(f.dd, currEncodedType)

	// an array can never return a nil slice. so no need to check f.array here.

	if rv.IsNil() {
		rv.Set(reflect.MakeSlice(f.ti.rt, containerLenS, containerLenS))
	}

	if containerLen == 0 {
		return
	}

	if rvcap, rvlen := rv.Len(), rv.Cap(); containerLenS > rvcap {
		if f.array { // !rv.CanSet()
			decErr(msgDecCannotExpandArr, rvcap, containerLenS)
		}
		rvn := reflect.MakeSlice(f.ti.rt, containerLenS, containerLenS)
		if rvlen > 0 {
			reflect.Copy(rvn, rv)
		}
		rv.Set(rvn)
	} else if containerLenS > rvlen {
		rv.SetLen(containerLenS)
	}

	rtelem := f.ti.rt.Elem()
	for rtelem.Kind() == reflect.Ptr {
		rtelem = rtelem.Elem()
	}
	fn := f.d.getDecFn(rtelem)
	for j := 0; j < containerLenS; j++ {
		f.d.decodeValue(rv.Index(j), fn)
	}
}
Esempio n. 24
0
// fillNilSlices sets default value on slices that are still nil.
func fillNilSlices(data interface{}) error {
	s := reflect.ValueOf(data).Elem()
	t := s.Type()

	for i := 0; i < s.NumField(); i++ {
		f := s.Field(i)
		tag := t.Field(i).Tag

		v := tag.Get("default")
		if len(v) > 0 {
			switch f.Interface().(type) {
			case []string:
				if f.IsNil() {
					// Treat the default as a comma separated slice
					vs := strings.Split(v, ",")
					for i := range vs {
						vs[i] = strings.TrimSpace(vs[i])
					}

					rv := reflect.MakeSlice(reflect.TypeOf([]string{}), len(vs), len(vs))
					for i, v := range vs {
						rv.Index(i).SetString(v)
					}
					f.Set(rv)
				}
			}
		}
	}
	return nil
}
Esempio n. 25
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
}
Esempio n. 26
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)
		}
	}
}
Esempio n. 27
0
// SetList sets the given list object's Items member have the elements given in
// objects.
// Returns an error if list is not a List type (does not have an Items member),
// or if any of the objects are not of the right type.
func SetList(list runtime.Object, objects []runtime.Object) error {
	itemsPtr, err := GetItemsPtr(list)
	if err != nil {
		return err
	}
	items, err := conversion.EnforcePtr(itemsPtr)
	if err != nil {
		return err
	}
	if items.Type() == objectSliceType {
		items.Set(reflect.ValueOf(objects))
		return nil
	}
	slice := reflect.MakeSlice(items.Type(), len(objects), len(objects))
	for i := range objects {
		dest := slice.Index(i)
		src, err := conversion.EnforcePtr(objects[i])
		if err != nil {
			return err
		}
		if src.Type().AssignableTo(dest.Type()) {
			dest.Set(src)
		} else if src.Type().ConvertibleTo(dest.Type()) {
			dest.Set(src.Convert(dest.Type()))
		} else {
			return fmt.Errorf("item[%d]: can't assign or convert %v into %v", i, src.Type(), dest.Type())
		}
	}
	items.Set(slice)
	return nil
}
Esempio n. 28
0
// shuffle returns the given rangeable list in a randomised order.
func shuffle(seq interface{}) (interface{}, error) {
	if seq == nil {
		return nil, errors.New("both count and seq must be provided")
	}

	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())
	}

	shuffled := reflect.MakeSlice(reflect.TypeOf(seq), seqv.Len(), seqv.Len())

	rand.Seed(time.Now().UTC().UnixNano())
	randomIndices := rand.Perm(seqv.Len())

	for index, value := range randomIndices {
		shuffled.Index(value).Set(seqv.Index(index))
	}

	return shuffled.Interface(), nil
}
Esempio n. 29
0
func (p *Decoder) unmarshalArray(pval *plistValue, val reflect.Value) {
	subvalues := pval.value.([]*plistValue)

	var n int
	if val.Kind() == reflect.Slice {
		// Slice of element values.
		// Grow slice.
		cnt := len(subvalues) + val.Len()
		if cnt >= val.Cap() {
			ncap := 2 * cnt
			if ncap < 4 {
				ncap = 4
			}
			new := reflect.MakeSlice(val.Type(), val.Len(), ncap)
			reflect.Copy(new, val)
			val.Set(new)
		}
		n = val.Len()
		val.SetLen(cnt)
	} else if val.Kind() == reflect.Array {
		if len(subvalues) > val.Cap() {
			panic(fmt.Errorf("plist: attempted to unmarshal %d values into an array of size %d", len(subvalues), val.Cap()))
		}
	} else {
		panic(&incompatibleDecodeTypeError{val.Type(), pval.kind})
	}

	// Recur to read element into slice.
	for _, sval := range subvalues {
		p.unmarshal(sval, val.Index(n))
		n++
	}
	return
}
Esempio n. 30
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
}