Ejemplo n.º 1
0
func (e *encodeState) writeMap(v reflect.Value, topLevel bool) {
	if v.IsNil() {
		return
	}
	if v.Type().Key().Kind() != reflect.String {
		abort(&EncodeTypeError{v.Type()})
	}
	offset := e.beginDoc()
	skipId := false
	if topLevel {
		idValue := v.MapIndex(idKey)
		if idValue.IsValid() {
			skipId = true
			e.encodeValue("_id", defaultFieldInfo, idValue)
		}
	}
	for _, k := range v.MapKeys() {
		sk := k.String()
		if !skipId || sk != "_id" {
			e.encodeValue(sk, defaultFieldInfo, v.MapIndex(k))
		}
	}
	e.WriteByte(0)
	e.endDoc(offset)
}
Ejemplo n.º 2
0
func (e *Encoder) encodeMap(av *dynamodb.AttributeValue, v reflect.Value, fieldTag tag) error {
	av.M = map[string]*dynamodb.AttributeValue{}
	for _, key := range v.MapKeys() {
		keyName := fmt.Sprint(key.Interface())
		if keyName == "" {
			return &InvalidMarshalError{msg: "map key cannot be empty"}
		}

		elemVal := v.MapIndex(key)
		elem := &dynamodb.AttributeValue{}
		err := e.encode(elem, elemVal, tag{})
		skip, err := keepOrOmitEmpty(fieldTag.OmitEmptyElem, elem, err)
		if err != nil {
			return err
		} else if skip {
			continue
		}

		av.M[keyName] = elem
	}
	if len(av.M) == 0 {
		encodeNull(av)
	}

	return nil
}
Ejemplo n.º 3
0
func convertMapToCFDictionaryHelper(m reflect.Value, helper func(reflect.Value) (cfTypeRef, error)) (C.CFDictionaryRef, error) {
	// assume m is a map, because our caller already checked
	if m.Type().Key().Kind() != reflect.String {
		// the map keys aren't strings
		return nil, &UnsupportedTypeError{m.Type()}
	}
	mapKeys := m.MapKeys()
	keys := make([]cfTypeRef, len(mapKeys))
	values := make([]cfTypeRef, len(mapKeys))
	// defer the release
	defer func() {
		for _, cfKey := range keys {
			cfRelease(cfTypeRef(cfKey))
		}
		for _, cfVal := range values {
			cfRelease(cfTypeRef(cfVal))
		}
	}()
	// create the keys and values slices
	for i, keyVal := range mapKeys {
		// keyVal is a Value representing a string
		cfStr := convertStringToCFString(keyVal.String())
		if cfStr == nil {
			return nil, errors.New("plist: could not convert string to CFStringRef")
		}
		keys[i] = cfTypeRef(cfStr)
		cfObj, err := helper(m.MapIndex(keyVal))
		if err != nil {
			return nil, err
		}
		values[i] = cfObj
	}
	return createCFDictionary(keys, values), nil
}
Ejemplo n.º 4
0
Archivo: encode.go Proyecto: 2thetop/go
func (me *mapEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) {
	if v.IsNil() {
		e.WriteString("null")
		return
	}
	e.WriteByte('{')

	// Extract and sort the keys.
	keys := v.MapKeys()
	sv := make([]reflectWithString, len(keys))
	for i, v := range keys {
		sv[i].v = v
		if err := sv[i].resolve(); err != nil {
			e.error(&MarshalerError{v.Type(), err})
		}
	}
	sort.Sort(byString(sv))

	for i, kv := range sv {
		if i > 0 {
			e.WriteByte(',')
		}
		e.string(kv.s, opts.escapeHTML)
		e.WriteByte(':')
		me.elemEnc(e, v.MapIndex(kv.v), opts)
	}
	e.WriteByte('}')
}
Ejemplo n.º 5
0
// decodeObjectInterface decodes the source value into map[string]interface{}
func decodeObjectInterface(s *decodeState, sv reflect.Value) map[string]interface{} {
	m := map[string]interface{}{}
	for _, key := range sv.MapKeys() {
		m[key.Interface().(string)] = decodeInterface(s, sv.MapIndex(key))
	}
	return m
}
Ejemplo n.º 6
0
func writeMap(w io.Writer, val reflect.Value) (err error) {
	key := val.Type().Key()
	if key.Kind() != reflect.String {
		return &MarshalError{val.Type()}
	}
	_, err = fmt.Fprint(w, "d")
	if err != nil {
		return
	}

	keys := val.MapKeys()

	// Sort keys

	svList := make(stringValueArray, len(keys))
	for i, key := range keys {
		svList[i].key = key.String()
		svList[i].value = val.MapIndex(key)
	}

	err = writeSVList(w, svList)
	if err != nil {
		return
	}

	_, err = fmt.Fprint(w, "e")
	if err != nil {
		return
	}
	return
}
Ejemplo n.º 7
0
// Validate checks whether the given value is writeable to this schema.
func (*NullSchema) Validate(v reflect.Value) bool {
	// Check if the value is something that can be null
	switch v.Kind() {
	case reflect.Interface:
		return v.IsNil()
	case reflect.Array:
		return v.Cap() == 0
	case reflect.Slice:
		return v.IsNil() || v.Cap() == 0
	case reflect.Map:
		return len(v.MapKeys()) == 0
	case reflect.String:
		return len(v.String()) == 0
	case reflect.Float32:
		// Should NaN floats be treated as null?
		return math.IsNaN(v.Float())
	case reflect.Float64:
		// Should NaN floats be treated as null?
		return math.IsNaN(v.Float())
	case reflect.Ptr:
		return v.IsNil()
	case reflect.Invalid:
		return true
	}

	// Nothing else in particular, so this should not validate?
	return false
}
Ejemplo n.º 8
0
func printMap(w io.Writer, tv reflect.Value, depth string) {
	fmt.Fprintf(w, "{\n")
	ss := make(sort.StringSlice, tv.Len())
	i := 0
	for _, kval := range tv.MapKeys() {
		if kval.Kind() == reflect.Interface {
			kval = kval.Elem()
		}

		if kval.Kind() != reflect.String {
			continue
		}

		ss[i] = kval.String()
		i++
	}
	sort.Sort(ss)
	for _, k := range ss {
		val := tv.MapIndex(reflect.ValueOf(k))
		v := val.Interface()
		nd := depth + "  "
		for i := 0; i < len(k)+2; i++ {
			nd += " "
		}
		fmt.Fprintf(w, "  %s%s: ", depth, k)
		printValue(w, v, nd)
	}
	fmt.Fprintf(w, "%s}\n", depth)
}
Ejemplo n.º 9
0
func reflectMap(v reflect.Value) map[interface{}]interface{} {
	switch v.Kind() {
	case reflect.Struct:
		m := map[interface{}]interface{}{}
		for i := 0; i < v.NumField(); i++ {
			sf := v.Type().Field(i)
			if sf.PkgPath != "" && !sf.Anonymous {
				continue // unexported
			}

			k := sf.Name
			v := v.Field(i).Interface()

			m[k] = v
		}
		return m
	case reflect.Map:
		m := map[interface{}]interface{}{}
		for _, mk := range v.MapKeys() {
			k := ""
			if mk.Interface() != nil {
				k = fmt.Sprintf("%v", mk.Interface())
			}
			v := v.MapIndex(mk).Interface()

			m[k] = v
		}
		return m
	default:
		return nil
	}
}
Ejemplo n.º 10
0
func deepCopyMap(src, dst reflect.Value, t reflect.Type) {
	for _, key := range src.MapKeys() {
		var nkey, nval reflect.Value
		if key.IsValid() && key.CanSet() {
			if key.Kind() == reflect.Ptr {
				nkey = reflect.New(key.Elem().Type())
			} else {
				nkey = reflect.New(key.Type())
				nkey = reflect.Indirect(nkey)
			}
			s := reflect.Indirect(key)
			d := reflect.Indirect(nkey)
			tt := s.Type()
			deepCopy(s, d, tt)
		} else {
			nkey = key
		}
		if val := src.MapIndex(key); val.IsValid() && val.CanSet() {
			if val.Kind() == reflect.Ptr {
				nval = reflect.New(val.Elem().Type())
			} else {
				nval = reflect.New(val.Type())
				nval = reflect.Indirect(nval)
			}
			s := reflect.Indirect(val)
			d := reflect.Indirect(nval)
			tt := s.Type()
			deepCopy(s, d, tt)
		} else {
			nval = val
		}
		dst.SetMapIndex(nkey, nval)
	}
}
Ejemplo n.º 11
0
func (m Master) retrieveValues(db *sql.DB, rv reflect.Value, cfgs ...interface{}) (idField reflect.Value, fields []string, holders []string, values []interface{}, table string, err error) {
	table = strings.ToLower(rv.Type().Name()) + "s"
	// var insertNull bool
	for _, c := range cfgs {
		switch c.(type) {
		// case InsertNull:
		// 	insertNull = true
		case TableName:
			table = string(c.(TableName))
		}
	}

	// _ = insertNull
	switch rv.Kind() {
	case reflect.Struct:
		idField, fields, holders, values, err = m.walkStruct(rv)
	case reflect.Map:
		if rv.Type().Key().Kind() != reflect.String {
			err = fmt.Errorf("sqlkungfu: Insert(map key is %s, want string)", rv.Type().Key().Kind())
			return
		}
		for _, k := range rv.MapKeys() {
			fields = append(fields, m.quoteColumn(k.String()))
			holders = append(holders, "?")
			values = append(values, rv.MapIndex(k).Interface())
		}
	}
	return
}
Ejemplo n.º 12
0
//AnySettableValue find if exist one value that you can set.
func AnySettableValue(val reflect.Value) bool {
	switch val.Kind() {
	case reflect.Array:
		for i := 0; i < val.Type().Len(); i++ {
			if AnySettableValue(val.Index(i)) {
				return true
			}
		}
	case reflect.Interface:
		return AnySettableValue(val.Elem())
	case reflect.Map:
		for _, key := range val.MapKeys() {
			if AnySettableValue(val.MapIndex(key)) {
				return true
			}
		}
	case reflect.Ptr:
		return AnySettableValue(val.Elem())
	case reflect.Slice:
		for i := 0; i < val.Len(); i++ {
			if AnySettableValue(val.Index(i)) {
				return true
			}
		}
	case reflect.Struct:
		for i := 0; i < val.Type().NumField(); i++ {
			if AnySettableValue(val.Field(i)) {
				return true
			}
		}
	default:
		return val.CanSet()
	}
	return false
}
Ejemplo n.º 13
0
func valEq(t *testing.T, name string, actual, expected reflect.Value) {
	switch expected.Kind() {
	case reflect.Slice:
		// Check the type/length/element type
		if !eq(t, name+" (type)", actual.Kind(), expected.Kind()) ||
			!eq(t, name+" (len)", actual.Len(), expected.Len()) ||
			!eq(t, name+" (elem)", actual.Type().Elem(), expected.Type().Elem()) {
			return
		}

		// Check value equality for each element.
		for i := 0; i < actual.Len(); i++ {
			valEq(t, fmt.Sprintf("%s[%d]", name, i), actual.Index(i), expected.Index(i))
		}

	case reflect.Ptr:
		// Check equality on the element type.
		valEq(t, name, actual.Elem(), expected.Elem())
	case reflect.Map:
		if !eq(t, name+" (len)", actual.Len(), expected.Len()) {
			return
		}
		for _, key := range expected.MapKeys() {
			expectedValue := expected.MapIndex(key)
			actualValue := actual.MapIndex(key)
			if actualValue.IsValid() {
				valEq(t, fmt.Sprintf("%s[%s]", name, key), actualValue, expectedValue)
			} else {
				t.Errorf("Expected key %s not found", key)
			}
		}
	default:
		eq(t, name, actual.Interface(), expected.Interface())
	}
}
Ejemplo n.º 14
0
func (e *Encoder) encodeMap(by []byte, m reflect.Value, strTable map[string]int, ptrTable map[uintptr]int) []byte {

	keys := m.MapKeys()

	l := len(keys)

	by = append(by, typeHASH)
	by = varint(by, uint(l))

	if e.PerlCompat {
		for _, k := range keys {
			by = e.encodeString(by, k.String(), true, strTable)
			v := m.MapIndex(k)
			by = e.encodeScalar(by, v, false, strTable, ptrTable)
		}
	} else {
		for _, k := range keys {
			by, _ = e.encode(by, k, true, strTable, ptrTable)
			v := m.MapIndex(k)
			by, _ = e.encode(by, v, false, strTable, ptrTable)
		}
	}

	return by
}
Ejemplo n.º 15
0
func approxDataSize(rv reflect.Value) (sum int) {
	switch rk := rv.Kind(); rk {
	case reflect.Invalid:
	case reflect.Ptr, reflect.Interface:
		sum += int(rv.Type().Size())
		sum += approxDataSize(rv.Elem())
	case reflect.Slice:
		sum += int(rv.Type().Size())
		for j := 0; j < rv.Len(); j++ {
			sum += approxDataSize(rv.Index(j))
		}
	case reflect.String:
		sum += int(rv.Type().Size())
		sum += rv.Len()
	case reflect.Map:
		sum += int(rv.Type().Size())
		for _, mk := range rv.MapKeys() {
			sum += approxDataSize(mk)
			sum += approxDataSize(rv.MapIndex(mk))
		}
	case reflect.Struct:
		//struct size already includes the full data size.
		//sum += int(rv.Type().Size())
		for j := 0; j < rv.NumField(); j++ {
			sum += approxDataSize(rv.Field(j))
		}
	default:
		//pure value types
		sum += int(rv.Type().Size())
	}
	return
}
Ejemplo n.º 16
0
func (d *decoder) mapCopy(src reflect.Value, dst reflect.Value) error {
	sv := src.MapKeys()
	dt := dst.Type().Elem()

	for i := range sv {
		ot := reflect.New(dt)

		if dt.Kind() == reflect.Ptr {
			ot = reflect.New(ot.Type().Elem())
		}

		d.pushPath(sv[i].String())
		err := d.decode(src.MapIndex(sv[i]), ot)
		if err != nil && err != ErrIncompatStruct {
			err = errors.New(d.pathString() + err.Error())
			d.path = nil
			return err
		}
		d.popPath()

		if err == nil {
			dst.SetMapIndex(sv[i], ot.Elem())
		}
	}
	return nil
}
// FindValueTypesInKnownMap finds out all value types in this level in a known map.
func (s StringKeyMapTypeSections) FindValueTypesInKnownMap(key string, v reflect.Value, noOfArrayLv int) (section StringKeyMapTypeSection, isMap bool) {
	if v.Kind() == reflect.Map {
		i := reflect.Invalid
		if len(v.MapKeys()) > 0 {
			i = reflect.Map
		}
		r := StringKeyMapTypeSection{key, noOfArrayLv, StringKeyMapTypeMap{}, i}
		newTypeFound := false
		for _, x := range v.MapKeys() {
			t, known := s.CheckIfValueTypeAlreadyKnown(x.String(), noOfArrayLv)
			if known {
				r.TypeMap[x.String()] = t
			} else {
				k := FindTypeForValue(v.MapIndex(x))
				if k == reflect.Invalid {
					return StringKeyMapTypeSection{}, false
				}
				r.TypeMap[x.String()] = k
				newTypeFound = true
			}
		}
		if newTypeFound {
			s.RemoveElemInSections(key, noOfArrayLv)
		}
		return r, true
	}
	return StringKeyMapTypeSection{}, false
}
Ejemplo n.º 18
0
func (d *mapAsMapDecoder) decode(dv, sv reflect.Value) {
	dt := dv.Type()
	dv.Set(reflect.MakeMap(reflect.MapOf(dt.Key(), dt.Elem())))

	var mapKey reflect.Value
	var mapElem reflect.Value

	keyType := dv.Type().Key()
	elemType := dv.Type().Elem()

	for _, sElemKey := range sv.MapKeys() {
		var dElemKey reflect.Value
		var dElemVal reflect.Value

		if !mapKey.IsValid() {
			mapKey = reflect.New(keyType).Elem()
		} else {
			mapKey.Set(reflect.Zero(keyType))
		}
		dElemKey = mapKey

		if !mapElem.IsValid() {
			mapElem = reflect.New(elemType).Elem()
		} else {
			mapElem.Set(reflect.Zero(elemType))
		}
		dElemVal = mapElem

		d.keyDec(dElemKey, sElemKey)
		d.elemDec(dElemVal, sv.MapIndex(sElemKey))

		dv.SetMapIndex(dElemKey, dElemVal)
	}
}
Ejemplo n.º 19
0
func (me *mapEncoder) encode(e *encodeState, v reflect.Value) {
	isSet := v.Type() == setType
	isKMap := v.Type() == keywordMapType
	sep := ", "
	if isSet {
		e.WriteByte('#')
		sep = " "
	}
	if v.IsNil() {
		e.WriteString("{}")
		return
	}
	e.WriteByte('{')
	for i, k := range v.MapKeys() {
		if i > 0 {
			e.WriteString(sep)
		}
		if !isKMap {
			me.keyEnc(e, k)
		} else {
			me.keyEnc(e, reflect.ValueOf(Keyword(k.String())))
		}
		if !isSet {
			e.WriteByte(' ')
			me.elemEnc(e, v.MapIndex(k))
		}
	}
	e.WriteByte('}')
}
Ejemplo n.º 20
0
func (d *mapAsStructDecoder) decode(dv, sv reflect.Value) {
	for _, kv := range sv.MapKeys() {
		var f *field
		var fieldDec decoderFunc
		key := []byte(kv.String())
		for i := range d.fields {
			ff := &d.fields[i]
			ffd := d.fieldDecs[i]
			if bytes.Equal(ff.nameBytes, key) {
				f = ff
				fieldDec = ffd
				break
			}
			if f == nil && ff.equalFold(ff.nameBytes, key) {
				f = ff
				fieldDec = ffd
			}
		}

		if f == nil {
			continue
		}

		dElemVal := fieldByIndex(dv, f.index)
		sElemVal := sv.MapIndex(kv)

		if !sElemVal.IsValid() || !dElemVal.CanSet() {
			continue
		}

		fieldDec(dElemVal, sElemVal)
	}
}
Ejemplo n.º 21
0
func (enc *Encoder) eMap(key Key, rv reflect.Value) {
	rt := rv.Type()
	if rt.Key().Kind() != reflect.String {
		encPanic(errNonString)
	}

	// Sort keys so that we have deterministic output. And write keys directly
	// underneath this key first, before writing sub-structs or sub-maps.
	var mapKeysDirect, mapKeysSub []string
	for _, mapKey := range rv.MapKeys() {
		k := mapKey.String()
		if typeIsHash(tomlTypeOfGo(rv.MapIndex(mapKey))) {
			mapKeysSub = append(mapKeysSub, k)
		} else {
			mapKeysDirect = append(mapKeysDirect, k)
		}
	}

	var writeMapKeys = func(mapKeys []string) {
		sort.Strings(mapKeys)
		for _, mapKey := range mapKeys {
			mrv := rv.MapIndex(reflect.ValueOf(mapKey))
			if isNil(mrv) {
				// Don't write anything for nil fields.
				continue
			}
			enc.encode(key.add(mapKey), mrv)
		}
	}
	writeMapKeys(mapKeysDirect)
	writeMapKeys(mapKeysSub)
}
Ejemplo n.º 22
0
// v1 and v2 are known to have the same type.
func equalAny(v1, v2 reflect.Value) bool {
	if v1.Type() == protoMessageType {
		m1, _ := v1.Interface().(Message)
		m2, _ := v2.Interface().(Message)
		return Equal(m1, m2)
	}
	switch v1.Kind() {
	case reflect.Bool:
		return v1.Bool() == v2.Bool()
	case reflect.Float32, reflect.Float64:
		return v1.Float() == v2.Float()
	case reflect.Int32, reflect.Int64:
		return v1.Int() == v2.Int()
	case reflect.Map:
		if v1.Len() != v2.Len() {
			return false
		}
		for _, key := range v1.MapKeys() {
			val2 := v2.MapIndex(key)
			if !val2.IsValid() {
				// This key was not found in the second map.
				return false
			}
			if !equalAny(v1.MapIndex(key), val2) {
				return false
			}
		}
		return true
	case reflect.Ptr:
		return equalAny(v1.Elem(), v2.Elem())
	case reflect.Slice:
		if v1.Type().Elem().Kind() == reflect.Uint8 {
			// short circuit: []byte
			if v1.IsNil() != v2.IsNil() {
				return false
			}
			return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte))
		}

		if v1.Len() != v2.Len() {
			return false
		}
		for i := 0; i < v1.Len(); i++ {
			if !equalAny(v1.Index(i), v2.Index(i)) {
				return false
			}
		}
		return true
	case reflect.String:
		return v1.Interface().(string) == v2.Interface().(string)
	case reflect.Struct:
		return equalStruct(v1, v2)
	case reflect.Uint32, reflect.Uint64:
		return v1.Uint() == v2.Uint()
	}

	// unknown type, so not a protocol buffer
	log.Printf("proto: don't know how to compare %v", v1)
	return false
}
Ejemplo n.º 23
0
func encodeMap(val reflect.Value) ([]byte, error) {
	var t = val.Type()

	if t.Key().Kind() != reflect.String {
		return nil, fmt.Errorf("xmlrpc encode error: only maps with string keys are supported")
	}

	var b bytes.Buffer

	b.WriteString("<struct>")

	keys := val.MapKeys()

	for i := 0; i < val.Len(); i++ {
		key := keys[i]
		kval := val.MapIndex(key)

		b.WriteString("<member>")
		b.WriteString(fmt.Sprintf("<name>%s</name>", key.String()))

		p, err := encodeValue(kval)

		if err != nil {
			return nil, err
		}

		b.Write(p)
		b.WriteString("</member>")
	}

	b.WriteString("</struct>")

	return b.Bytes(), nil
}
Ejemplo n.º 24
0
// Pretty-print any random data we get back from the server
func genericLogData(name string, v reflect.Value, indent string, skip int) {
	prefix := "->" + indent
	if name != "" {
		prefix = "-> " + indent + name + ":"
	}

	// For pointers and interfaces, just grab the underlying value and try again
	if v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
		genericLogData(name, v.Elem(), indent, skip)
		return
	}

	// Only print if skip is 0.  Recursive calls should indent or decrement skip, depending on if anything was
	// printed.
	var skipped bool
	if skip == 0 {
		skipped = false
		indent = indent + "  "
	} else {
		skipped = true
		skip = skip - 1
	}

	switch v.Kind() {
	case reflect.Struct:
		if !skipped {
			Log("%s\n", prefix)
		}
		for f := 0; f < v.NumField(); f++ {
			name := v.Type().Field(f).Name
			genericLogData(name, v.Field(f), indent, skip)
		}
	case reflect.Array:
		fallthrough
	case reflect.Slice:
		if !skipped {
			Log("%s\n", prefix)
		}
		for i := 0; i < v.Len(); i++ {
			genericLogData("", v.Index(i), indent, skip)
		}
	case reflect.Map:
		if !skipped {
			Log("%s\n", prefix)
		}
		for _, k := range v.MapKeys() {
			if name, ok := k.Interface().(string); ok {
				genericLogData(name, v.MapIndex(k), indent, skip)
			} else {
				genericLogData("Unknown field", v.MapIndex(k), indent, skip)
			}
		}
	default:
		if v.CanInterface() {
			Log("%s %v", prefix, v.Interface())
		} else {
			Log("%s <Invalid>", prefix)
		}
	}
}
Ejemplo n.º 25
0
func display(name string, v reflect.Value) {
	switch v.Kind() { //uint
	case reflect.Invalid:
		fmt.Printf("%s = invalid\n", name)
	case reflect.Slice, reflect.Array:
		for i := 0; i < v.Len(); i++ {
			display(fmt.Sprintf("%s[%d]", name, i), v.Index(i))
		}
	case reflect.Struct:
		for i := 0; i < v.NumField(); i++ {
			fieldPath := fmt.Sprintf("%s.%s", name, v.Type().Field(i).Name)
			display(fieldPath, v.Field(i))
		}
	case reflect.Map:
		for _, key := range v.MapKeys() {
			display(fmt.Sprintf("%s[%s]", name,
				formatAtom(key)), v.MapIndex(key))
		}
	case reflect.Ptr:
		if v.IsNil() {
			fmt.Printf("%s = nil\n", name)
		} else {
			display(fmt.Sprintf("(*%s)", name), v.Elem())
		}
	case reflect.Interface:
		if v.IsNil() {
			fmt.Printf("%s = nil\n", name)
		} else {
			fmt.Printf("%s.type = %s\n", name, v.Elem().Type())
			display(name+".value", v.Elem())
		}
	default: // basic types, channels, funcs
		fmt.Printf("%s = %s\n", name, formatAtom(v))
	}
}
Ejemplo n.º 26
0
func quietOutput(prefix string, v reflect.Value) {
	// For pointers and interfaces, just grab the underlying value and try again
	if v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
		quietOutput(prefix, v.Elem())
		return
	}

	switch v.Kind() {
	case reflect.Struct:
		for f := 0; f < v.NumField(); f++ {
			name := v.Type().Field(f).Name
			quietOutput(prefix+name+" ", v.Field(f))
		}
	case reflect.Array:
		fallthrough
	case reflect.Slice:
		for i := 0; i < v.Len(); i++ {
			quietOutput(prefix, v.Index(i))
		}
	case reflect.Map:
		for _, k := range v.MapKeys() {
			if name, ok := k.Interface().(string); ok {
				quietOutput(prefix+name+" ", v.MapIndex(k))
			} else {
				quietOutput(prefix+"UnknownField", v.MapIndex(k))
			}
		}
	default:
		if v.CanInterface() {
			fmt.Printf("%s%v\n", prefix, v.Interface())
		} else {
			fmt.Printf("%s <Invalid>", prefix)
		}
	}
}
Ejemplo n.º 27
0
func (e *Encoder) encodeMap(by []byte, m reflect.Value, isRefNext bool, strTable map[string]int, ptrTable map[uintptr]int) ([]byte, error) {
	if e.PerlCompat && !isRefNext {
		by = append(by, typeREFN)
	}

	keys := m.MapKeys()
	by = append(by, typeHASH)
	by = varint(by, uint(len(keys)))

	var err error
	if e.PerlCompat {
		for _, k := range keys {
			by = e.encodeString(by, k.String(), true, strTable)
			if by, err = e.encode(by, m.MapIndex(k), false, false, strTable, ptrTable); err != nil {
				return by, err
			}
		}
	} else {
		for _, k := range keys {
			if by, err = e.encode(by, k, true, false, strTable, ptrTable); err != nil {
				return by, err
			}

			if by, err = e.encode(by, m.MapIndex(k), false, false, strTable, ptrTable); err != nil {
				return by, err
			}
		}
	}

	return by, nil
}
Ejemplo n.º 28
0
// encodeMap treats the map represented by the passed reflection value as a
// variable-length array of 2-element structures whose fields are of the same
// type as the map keys and elements and appends its XDR encoded representation
// to the Encoder's data.
//
// A MarshalError is returned if any issues are encountered while encoding
// the elements.
func (enc *Encoder) encodeMap(v reflect.Value) (err error) {
	dataLen := v.Len()
	if uint(dataLen) > math.MaxUint32 {
		err = marshalError("encodeMap", ErrOverflow, errMaxXdr, dataLen)
		return
	}
	err = enc.EncodeUint(uint32(dataLen))
	if err != nil {
		return
	}

	// Encode each key and value according to their type.
	for _, key := range v.MapKeys() {
		err = enc.encode(key)
		if err != nil {
			return
		}

		err = enc.encode(v.MapIndex(key))
		if err != nil {
			return
		}
	}
	return
}
Ejemplo n.º 29
0
func (w *Writer) writeMap(v interface{}, rv reflect.Value) (err error) {
	w.setRef(v)
	s := w.Stream
	if err = s.WriteByte(TagMap); err == nil {
		if count := rv.Len(); count > 0 {
			if err = w.writeInt(count); err == nil {
				if err = s.WriteByte(TagOpenbrace); err == nil {
					keys := rv.MapKeys()
					for i := range keys {
						if err = w.WriteValue(keys[i]); err != nil {
							return err
						}
						if err = w.WriteValue(rv.MapIndex(keys[i])); err != nil {
							return err
						}
					}
					err = s.WriteByte(TagClosebrace)
				}
			}
		} else if err = s.WriteByte(TagOpenbrace); err == nil {
			err = s.WriteByte(TagClosebrace)
		}
	}
	return err
}
Ejemplo n.º 30
0
func (w *Writer) writeMap(v reflect.Value) error {
	fm := labelFormatter(v.Type().Key())
	if fm == nil {
		return ErrUnsupportedType
	}
	if !v.IsNil() {
		var err error
		for i, key := range v.MapKeys() {
			if i >= 1 {
				if _, err = w.w.WriteRune(w.Delimiter); err != nil {
					return err
				}
			}
			label, err := fm(key)
			if err != nil {
				return err
			}
			field, err := reflectValue(v.MapIndex(key))
			if err != nil {
				return err
			}
			if err = w.writeLabelAndField(label, field); err != nil {
				return err
			}
		}
	}
	return nil
}