Exemple #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()
}
Exemple #2
0
// Remove removes the first occurence of the given val. It returns true
// if an element was removed, false otherwise. Note that the first argument
// must a pointer to a slice, while the second one must be a valid element
// of the slice. Otherwise, this function will panic.
func Remove(slicePtr interface{}, val interface{}) bool {
	s := reflect.ValueOf(slicePtr)
	if s.Kind() != reflect.Ptr || s.Type().Elem().Kind() != reflect.Slice {
		panic(fmt.Errorf("first argument to Remove must be pointer to slice, not %T", slicePtr))
	}
	if s.IsNil() {
		return false
	}
	itr := s.Elem()
	v := reflect.ValueOf(val)
	if itr.Type().Elem() != v.Type() {
		panic(fmt.Errorf("second argument to Remove must be %s, not %s", itr.Type().Elem(), v.Type()))
	}
	vi := v.Interface()
	for ii := 0; ii < itr.Len(); ii++ {
		if reflect.DeepEqual(itr.Index(ii).Interface(), vi) {
			newSlice := reflect.MakeSlice(itr.Type(), itr.Len()-1, itr.Len()-1)
			reflect.Copy(newSlice, itr.Slice(0, ii))
			reflect.Copy(newSlice.Slice(ii, newSlice.Len()), itr.Slice(ii+1, itr.Len()))
			s.Elem().Set(newSlice)
			return true
		}
	}
	return false
}
func main() {

	src := reflect.ValueOf([]int{1, 2, 3})
	/* make sure the dest space is larger than src */
	dest := reflect.ValueOf([]int{10, 20, 30})

	cnt := reflect.Copy(dest, src)
	data := dest.Interface().([]int)
	data[0] = 100
	fmt.Println(cnt)
	fmt.Println(src)
	fmt.Println(dest)

	elmt := map[string]int{"age": 10}
	data2 := make([]map[string]int, 1)
	data2[0] = elmt

	src2 := reflect.ValueOf(data2)
	dest2 := reflect.ValueOf(make([]map[string]int, 1))
	cnt2 := reflect.Copy(dest2, src2)
	data2[0]["age"] = 100 /* they share the same map */

	fmt.Println(cnt2)
	fmt.Println(src2)
	fmt.Println(dest2)
}
Exemple #4
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
	}
}
Exemple #5
0
func (s RSlice) overwrite(offset int, source *reflect.Value) {
	if offset == 0 {
		reflect.Copy(*s.Value, *source)
	} else {
		reflect.Copy(s.Slice(offset, s.Len()), *source)
	}
}
Exemple #6
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()
}
Exemple #7
0
func TestRaceReflectCopyWW(t *testing.T) {
	ch := make(chan bool, 1)
	a := make([]byte, 2)
	v := reflect.ValueOf(a)
	go func() {
		reflect.Copy(v, v)
		ch <- true
	}()
	reflect.Copy(v, v)
	<-ch
}
Exemple #8
0
// encodeFixedArray writes the XDR encoded representation of each element
// in the passed array represented by the reflection value to the encapsulated
// writer and returns the number of bytes written.  The ignoreOpaque flag
// controls whether or not uint8 (byte) elements should be encoded individually
// or as a fixed sequence of opaque data.
//
// A MarshalError is returned if any issues are encountered while encoding
// the array elements.
//
// Reference:
// 	RFC Section 4.12 - Fixed-Length Array
// 	Individually XDR encoded array elements
func (enc *Encoder) encodeFixedArray(v reflect.Value, ignoreOpaque bool) (int, error) {
	// Treat [#]byte (byte is alias for uint8) as opaque data unless ignored.
	if !ignoreOpaque && v.Type().Elem().Kind() == reflect.Uint8 {
		// Create a slice of the underlying array for better efficiency
		// when possible.  Can't create a slice of an unaddressable
		// value.
		if v.CanAddr() {
			return enc.EncodeFixedOpaque(v.Slice(0, v.Len()).Bytes())
		}

		// When the underlying array isn't addressable fall back to
		// copying the array into a new slice.  This is rather ugly, but
		// the inability to create a constant slice from an
		// unaddressable array is a limitation of Go.
		slice := make([]byte, v.Len(), v.Len())
		reflect.Copy(reflect.ValueOf(slice), v)
		return enc.EncodeFixedOpaque(slice)
	}

	// Encode each array element.
	var n int
	for i := 0; i < v.Len(); i++ {
		n2, err := enc.encode(v.Index(i))
		n += n2
		if err != nil {
			return n, err
		}
	}

	return n, nil
}
Exemple #9
0
func (fs *FlagSet) parseNextItem(args []string) ([]string, error) {
	if strings.HasPrefix(args[0], "--") {
		return fs.parseLongFlag(args)
	} else if strings.HasPrefix(args[0], "-") {
		return fs.parseShortFlagCluster(args)
	}

	if fs.Verbs != nil {
		verb, ok := fs.Verbs[args[0]]
		if !ok {
			return args, fmt.Errorf("Unknown verb: %s", args[0])
		}
		err := verb.Parse(args[1:])
		if err != nil {
			return args, err
		}
		return []string{}, nil
	}
	if fs.remainderFlag != nil {
		remainder := reflect.MakeSlice(fs.remainderFlag.value.Type(), len(args), len(args))
		reflect.Copy(remainder, reflect.ValueOf(args))
		fs.remainderFlag.value.Set(remainder)
		return []string{}, nil
	}
	return args, fmt.Errorf("Invalid trailing arguments: %v", args)
}
Exemple #10
0
func decodeSlice(d *decodeState, kind int, value reflect.Value) {
	if kind != kindArray {
		d.saveErrorAndSkip(kind, value.Type())
		return
	}
	v := value.(*reflect.SliceValue)
	t := v.Type().(*reflect.SliceType)
	offset := d.beginDoc()
	i := 0
	for {
		kind, _ := d.scanKindName()
		if kind == 0 {
			break
		}
		if i >= v.Cap() {
			newcap := v.Cap() + v.Cap()/2
			if newcap < 4 {
				newcap = 4
			}
			newv := reflect.MakeSlice(t, v.Len(), newcap)
			reflect.Copy(newv, v)
			v.Set(newv)
		}
		if i >= v.Len() {
			v.SetLen(i + 1)
		}
		d.decodeValue(kind, v.Elem(i))
		i += 1
	}
	d.endDoc(offset)
}
Exemple #11
0
/*
	Create a new memory container and copy contents across to it.
	Returns nil when reallocation fails.
*/
func Reallocate(container interface{}, length, capacity int) (r interface{}) {
	switch c := container.(type) {
	case Resizeable:
		c.Reallocate(length, capacity)
		r = c

	default:
		if c := reflect.ValueOf(container); c.Kind() == reflect.Slice {
			if length > capacity {
				length = capacity
			}
			if c.Cap() != capacity {
				n := reflect.MakeSlice(c.Type(), length, capacity)
				reflect.Copy(n, c)
				c = n
			}

			if c.Len() != length {
				c = makeAddressable(c)
				c.SetLen(length)
			}

			r = c.Interface()
		}
	}
	return
}
Exemple #12
0
func encodeByteArray(b []byte, v reflect.Value) []byte {
	n := v.Len()

	if n < (0xec - 0xe0) {
		b = append(b, byte(0xe0+n))
	} else {
		b = encodeK4(b, 0xec, uint64(n))
	}

	// Fast path for when the array is addressable (which it almost
	// always will be).
	if v.CanAddr() {
		return append(b, v.Slice(0, n).Bytes()...)
	}

	i := len(b)
	j := i + n

	if j > cap(b) {
		t := make([]byte, i, j)
		copy(t, b)
		b = t
	}

	reflect.Copy(reflect.ValueOf(b[i:j]), v)
	return b[:j]
}
Exemple #13
0
func ArraySort(data interface{}) interface{} {
	//建立一份拷贝数据
	dataValue := reflect.ValueOf(data)
	dataType := dataValue.Type()
	dataValueLen := dataValue.Len()

	dataResult := reflect.MakeSlice(dataType, dataValueLen, dataValueLen)
	reflect.Copy(dataResult, dataValue)

	//排序
	dataElemType := dataType.Elem()
	var result interface{}
	if dataElemType.Kind() == reflect.Int {
		intArray := dataResult.Interface().([]int)
		sort.Sort(sort.IntSlice(intArray))
		result = intArray
	} else if dataElemType.Kind() == reflect.String {
		stringArray := dataResult.Interface().([]string)
		sort.Sort(sort.StringSlice(stringArray))
		result = stringArray
	} else {
		panic("invalid sort type " + fmt.Sprintf("%v", dataElemType))
	}
	return result
}
Exemple #14
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
}
Exemple #15
0
func decodeSliceElems(s *Stream, val reflect.Value, elemdec decoder) error {
	i := 0
	for ; ; i++ {
		// grow slice if necessary
		if i >= val.Cap() {
			newcap := val.Cap() + val.Cap()/2
			if newcap < 4 {
				newcap = 4
			}
			newv := reflect.MakeSlice(val.Type(), val.Len(), newcap)
			reflect.Copy(newv, val)
			val.Set(newv)
		}
		if i >= val.Len() {
			val.SetLen(i + 1)
		}
		// decode into element
		if err := elemdec(s, val.Index(i)); err == EOL {
			break
		} else if err != nil {
			return addErrorContext(err, fmt.Sprint("[", i, "]"))
		}
	}
	if i < val.Len() {
		val.SetLen(i)
	}
	return nil
}
Exemple #16
0
func copyAny(out, in reflect.Value) {
	switch in.Kind() {
	case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
		reflect.String, reflect.Uint32, reflect.Uint64:
		out.Set(in)
	case reflect.Ptr:
		if in.IsNil() {
			return
		}
		out.Set(reflect.New(in.Type().Elem()))
		copyAny(out.Elem(), in.Elem())
	case reflect.Slice:
		if in.IsNil() {
			return
		}
		n := in.Len()
		out.Set(reflect.MakeSlice(in.Type(), n, n))
		switch in.Type().Elem().Kind() {
		case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
			reflect.String, reflect.Uint32, reflect.Uint64, reflect.Uint8:
			reflect.Copy(out, in)
		default:
			for i := 0; i < n; i++ {
				copyAny(out.Index(i), in.Index(i))
			}
		}
	case reflect.Struct:
		copyStruct(out, in)
	default:
		// unknown type, so not a protocol buffer
		log.Printf("proto: don't know how to copy %v", in)
	}
}
Exemple #17
0
func setCustomType(base structPointer, f field, value interface{}) {
	if value == nil {
		return
	}
	v := reflect.ValueOf(value).Elem()
	t := reflect.TypeOf(value).Elem()
	kind := t.Kind()
	switch kind {
	case reflect.Slice:
		slice := reflect.MakeSlice(t, v.Len(), v.Cap())
		reflect.Copy(slice, v)
		oldHeader := structPointer_GetSliceHeader(base, f)
		oldHeader.Data = slice.Pointer()
		oldHeader.Len = v.Len()
		oldHeader.Cap = v.Cap()
	default:
		l := 1
		size := reflect.TypeOf(value).Elem().Size()
		if kind == reflect.Array {
			l = reflect.TypeOf(value).Elem().Len()
			size = reflect.TypeOf(value).Size()
		}
		total := int(size) * l
		structPointer_Copy(toStructPointer(reflect.ValueOf(value)), structPointer_Add(base, f), total)
	}
}
Exemple #18
0
// grow grows the slice s so that it can hold extra more values, allocating
// more capacity if needed. It also returns the old and new slice lengths.
func grow(s reflect.Value, extra int) (reflect.Value, int, int) {
	i0 := s.Len()
	i1 := i0 + extra
	if i1 < i0 {
		panic("reflect.Append: slice overflow")
	}
	m := s.Cap()
	if i1 <= m {
		return s.Slice(0, i1), i0, i1
	}
	if m == 0 {
		m = extra
	} else {
		for m < i1 {
			if i0 < 1024 {
				m += m
			} else {
				m += m / 4
			}
		}
	}
	t := reflect.MakeSlice(s.Type(), i1, m)
	reflect.Copy(t, s)
	return t, i0, i1
}
Exemple #19
0
// set attempts to assign src to dst by either setting, copying or otherwise.
//
// set is a bit more lenient when it comes to assignment and doesn't force an as
// strict ruleset as bare `reflect` does.
func set(dst, src reflect.Value, output Argument) error {
	dstType := dst.Type()
	srcType := src.Type()

	switch {
	case dstType.AssignableTo(src.Type()):
		dst.Set(src)
	case dstType.Kind() == reflect.Array && srcType.Kind() == reflect.Slice:
		if !dstType.Elem().AssignableTo(r_byte) {
			return fmt.Errorf("abi: cannot unmarshal %v in to array of elem %v", src.Type(), dstType.Elem())
		}

		if dst.Len() < output.Type.SliceSize {
			return fmt.Errorf("abi: cannot unmarshal src (len=%d) in to dst (len=%d)", output.Type.SliceSize, dst.Len())
		}
		reflect.Copy(dst, src)
	case dstType.Kind() == reflect.Interface:
		dst.Set(src)
	case dstType.Kind() == reflect.Ptr:
		return set(dst.Elem(), src, output)
	default:
		return fmt.Errorf("abi: cannot unmarshal %v in to %v", src.Type(), dst.Type())
	}
	return nil
}
Exemple #20
0
// FormatSmart marshals value into a []byte according to the following rules:
//   * string:        untouched
//   * bool:          converted to `True` or `False` (to match pyjuju)
//   * int or float:  converted to sensible strings
//   * []string:      joined by `\n`s into a single string
//   * anything else: delegate to FormatYaml
func FormatSmart(value interface{}) ([]byte, error) {
	if value == nil {
		return nil, nil
	}
	v := reflect.ValueOf(value)
	switch kind := v.Kind(); kind {
	case reflect.String:
		return []byte(value.(string)), nil
	case reflect.Array:
		if v.Type().Elem().Kind() == reflect.String {
			slice := reflect.MakeSlice(reflect.TypeOf([]string(nil)), v.Len(), v.Len())
			reflect.Copy(slice, v)
			return []byte(strings.Join(slice.Interface().([]string), "\n")), nil
		}
	case reflect.Slice:
		if v.Type().Elem().Kind() == reflect.String {
			return []byte(strings.Join(value.([]string), "\n")), nil
		}
	case reflect.Bool:
		if value.(bool) {
			return []byte("True"), nil
		}
		return []byte("False"), nil
	case reflect.Map, reflect.Float32, reflect.Float64:
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
	default:
		return nil, fmt.Errorf("cannot marshal %#v", value)
	}
	return FormatYaml(value)
}
func (upckr *unpacker) unpackBlob(count int, isMapKey bool) (interface{}, error) {
	theType := upckr.buffer[upckr.offset] & 0xff
	upckr.offset++
	count--
	var val interface{}

	switch theType {
	case ParticleType.STRING:
		val = string(upckr.buffer[upckr.offset : upckr.offset+count])

	case ParticleType.BLOB:
		if isMapKey {
			b := reflect.Indirect(reflect.New(reflect.ArrayOf(count, reflect.TypeOf(byte(0)))))
			reflect.Copy(b, reflect.ValueOf(upckr.buffer[upckr.offset:upckr.offset+count]))

			val = b.Interface()
		} else {
			b := make([]byte, count)
			copy(b, upckr.buffer[upckr.offset:upckr.offset+count])
			val = b
		}

	case ParticleType.GEOJSON:
		val = NewGeoJSONValue(string(upckr.buffer[upckr.offset : upckr.offset+count]))

	default:
		panic(NewAerospikeError(SERIALIZE_ERROR, fmt.Sprintf("Error while unpacking BLOB. Type-header with code `%d` not recognized.", theType)))
	}
	upckr.offset += count

	return val, nil
}
Exemple #22
0
func (self *structBuilder) Elem(i int) Builder {
	if self == nil || i < 0 {
		return nobuilder
	}
	switch v := self.val.(type) {
	case *reflect.ArrayValue:
		if i < v.Len() {
			return &structBuilder{val: v.Elem(i)}
		}
	case *reflect.SliceValue:
		if i > v.Cap() {
			n := v.Cap()
			if n < 8 {
				n = 8
			}
			for n <= i {
				n *= 2
			}
			nv := reflect.MakeSlice(v.Type().(*reflect.SliceType), v.Len(), n)
			reflect.Copy(nv, v)
			v.Set(nv)
		}
		if v.Len() <= i && i < v.Cap() {
			v.SetLen(i + 1)
		}
		if i < v.Len() {
			return &structBuilder{val: v.Elem(i)}
		}
	}
	return nobuilder
}
Exemple #23
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")
	}
}
Exemple #24
0
func (b *structBuilder) Elem(i int) builder {
	if b == nil || i < 0 {
		return nobuilder
	}
	switch v := b.val; v.Kind() {
	case reflect.Array:
		if i < v.Len() {
			return &structBuilder{val: v.Index(i)}
		}
	case reflect.Slice:
		if i >= v.Cap() {
			n := v.Cap()
			if n < 8 {
				n = 8
			}
			for n <= i {
				n *= 2
			}
			nv := reflect.MakeSlice(v.Type(), v.Len(), n)
			reflect.Copy(nv, v)
			v.Set(nv)
		}
		if v.Len() <= i && i < v.Cap() {
			v.SetLen(i + 1)
		}
		if i < v.Len() {
			return &structBuilder{val: v.Index(i)}
		}
	}
	return nobuilder
}
Exemple #25
0
func (p *printer) marshalSimple(typ reflect.Type, val reflect.Value) (string, []byte, error) {
	switch val.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return strconv.FormatInt(val.Int(), 10), nil, nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return strconv.FormatUint(val.Uint(), 10), nil, nil
	case reflect.Float32, reflect.Float64:
		return strconv.FormatFloat(val.Float(), 'g', -1, val.Type().Bits()), nil, nil
	case reflect.String:
		return val.String(), nil, nil
	case reflect.Bool:
		return strconv.FormatBool(val.Bool()), nil, nil
	case reflect.Array:
		if typ.Elem().Kind() != reflect.Uint8 {
			break
		}
		// [...]byte
		var bytes []byte
		if val.CanAddr() {
			bytes = val.Slice(0, val.Len()).Bytes()
		} else {
			bytes = make([]byte, val.Len())
			reflect.Copy(reflect.ValueOf(bytes), val)
		}
		return "", bytes, nil
	case reflect.Slice:
		if typ.Elem().Kind() != reflect.Uint8 {
			break
		}
		// []byte
		return "", val.Bytes(), nil
	}
	return "", nil, &UnsupportedTypeError{typ}
}
Exemple #26
0
func (builder *valueBuilder) Elem(i int) *valueBuilder {
	if i < 0 {
		panic(NewBsonError("negative index %v for array element", i))
	}
	switch builder.val.Kind() {
	case reflect.Array:
		if i < builder.val.Len() {
			return ValueBuilder(builder.val.Index(i))
		} else {
			panic(NewBsonError("array index %v out of bounds", i))
		}
	case reflect.Slice:
		if i >= builder.val.Cap() {
			n := builder.val.Cap()
			if n < 8 {
				n = 8
			}
			for n <= i {
				n *= 2
			}
			nv := reflect.MakeSlice(builder.val.Type(), builder.val.Len(), n)
			reflect.Copy(nv, builder.val)
			builder.val.Set(nv)
		}
		if builder.val.Len() <= i && i < builder.val.Cap() {
			builder.val.SetLen(i + 1)
		}
		if i < builder.val.Len() {
			return ValueBuilder(builder.val.Index(i))
		} else {
			panic(NewBsonError("internal error, realloc failed?"))
		}
	}
	panic(NewBsonError("unexpected type %s, expecting slice or array", builder.val.Type()))
}
Exemple #27
0
func (d *Decoder) decodeBinary(b []byte, v reflect.Value) error {
	if v.Kind() == reflect.Interface {
		buf := make([]byte, len(b))
		copy(buf, b)
		v.Set(reflect.ValueOf(buf))
		return nil
	}

	switch v.Interface().(type) {
	case []byte:
		if v.IsNil() || v.Cap() < len(b) {
			v.Set(reflect.MakeSlice(byteSliceType, len(b), len(b)))
		} else if v.Len() != len(b) {
			v.SetLen(len(b))
		}
		copy(v.Interface().([]byte), b)
	default:
		if v.Kind() == reflect.Array && v.Type().Elem().Kind() == reflect.Uint8 {
			reflect.Copy(v, reflect.ValueOf(b))
			break
		}
		return &UnmarshalTypeError{Value: "binary", Type: v.Type()}
	}

	return nil
}
Exemple #28
0
func TestSort(t *testing.T) {
	tests := []interface{}{
		[]int{3, 4, 6, 7, 2},
		[]uint{3, 4, 6, 7, 2},
		[]float64{3, 4, 6, 7, 2},
		[]string{"f", "d", "a", "c"},
		[]int{1},
		[]int{},
	}
	for _, v := range tests {
		vv := reflect.ValueOf(v)
		cpy := reflect.MakeSlice(vv.Type(), vv.Len(), vv.Len())
		reflect.Copy(cpy, vv)
		switch x := v.(type) {
		case []int:
			sort.Ints(x)
		case []uint:
			sort.Sort(uintslice(x))
		case []float64:
			sort.Float64s(x)
		case []string:
			sort.Strings(x)
		}
		reflectSortCompare(t, v, cpy)
	}
}
Exemple #29
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))
	}
}
Exemple #30
0
func main() {
	var a A
	a.A0 = append(a.A0, []int{1, 2, 3, 4, 5, 6, 7, 8, 9}...)
	a.A1 = append(a.A1, 9, 8, 7, 6)
	var n = reflect.Copy(reflect.ValueOf(a.A0), reflect.ValueOf(a.A1))
	fmt.Println(n, a) // 4 {[9 8 7 6 5 6 7 8 9] [9 8 7 6]}
}