Exemple #1
0
func writeMapMarshal(out *bufio.Writer, fi *FileInfo, s StructInfo) {
	out.WriteString(fmt.Sprintf("func (this %s) MarshalMsg(out []byte) ([]byte, error) {\n", s.Type))
	out.WriteString("var (\nerr error\n)\n")
	out.WriteString(fmt.Sprintf("size := uint32(len(this))\n"))
	out.WriteString(fmt.Sprintf("out = msgp.AppendMapHeader(out, size)\n"))
	out.WriteString("for k, v := range this {\n")

	//Marshal key
	if s.ReflectType.Key().PkgPath() == "" {
		elType := s.ReflectType.Key().Name()
		out.WriteString(fmt.Sprintf("out = msgp.Append%s(out, k)\n", strings.ToUpper(elType[:1])+elType[1:]))
	} else {
		if msgp.IsSupportMarshal(s.ReflectType.Key()) || fi.IsSupport(s.Type) {
			out.WriteString("out, err = k.MarshalMsg(out)\n")
		} else {
			out.WriteString("out, err = msgp.MarshalMsg(out, k)\n")
		}
		out.WriteString(errBlock)
	}

	//Marshal value
	if s.ReflectType.Elem().PkgPath() == "" {
		elType := s.ReflectType.Elem().Name()
		out.WriteString(fmt.Sprintf("out = msgp.Append%s(out, v)\n", strings.ToUpper(elType[:1])+elType[1:]))
	} else {
		if msgp.IsSupportMarshal(s.ReflectType.Elem()) || fi.IsSupport(s.Type) {
			out.WriteString("out, err = v.MarshalMsg(out)\n")
		} else {
			out.WriteString("out, err = msgp.MarshalMsg(out, v)\n")
		}
		out.WriteString(errBlock)
	}
	out.WriteString("}\n")
	out.WriteString(endBlock)
}
Exemple #2
0
func (this *FileInfo) addStruct(val reflect.Value) error {
	t := val.Type()
	Infof("Add struct %s", t.Name())

	item := StructInfo{
		Type:        t.Name(),
		ReflectType: t,
	}

	fields := getStructFields(val)
	for _, field := range fields {

		alias, stdType := this.getAlias(this.Packet, field.Type)
		el := FieldInfo{
			Name:        field.Tag,
			StructName:  field.Name,
			Type:        alias,
			IsStdType:   stdType,
			IsPointer:   field.Type.Kind() == reflect.Ptr,
			IsMarshal:   msgp.IsSupportMarshal(field.Type),
			IsUnmarshal: msgp.IsSupportUnmarshal(field.Type),
			ReflectType: field.Type,
		}

		switch field.Type.Kind() {
		case reflect.Slice, reflect.Array, reflect.Ptr:
			elType := field.Type.Elem()
			alias, stdType := this.getAlias(this.Packet, elType)

			el.ChildInfo = &FieldInfo{
				Type:        alias,
				IsStdType:   stdType,
				IsPointer:   false,
				IsMarshal:   msgp.IsSupportMarshal(elType),
				IsUnmarshal: msgp.IsSupportUnmarshal(elType),
				ReflectType: elType,
			}
		default:
			break
		}

		item.Fields = append(item.Fields, el)
		Infof("Field: %s (%s, %v)", field.Tag, field.Name, field.Type.Kind() == reflect.Ptr)
	}

	this.Structs[item.Type] = item

	return nil
}