Exemplo n.º 1
0
        public static byte[] Serialize <T>(T inst)
        {
            Type type = inst.GetType();

            if (!profiles.ContainsKey(type))
            {
                GenerateProfile(type);
            }
            SerializationProfile profile = profiles[type];

            byte[] data = new byte[profile.BufferLength];

            foreach (FieldMetadata field in profile.Fields)
            {
                object collect = type.GetField(field.FieldName).GetValue(inst);
                if (collect == null)
                {
                    throw new Exception("Value of field " + field.FieldName + " in class instance " + type.Name + " was null");
                }

                byte[] typedata = ObjectToRawData(collect, field.FieldLength);

                Array.Copy(typedata, 0, data, field.FieldBufferIndex, field.FieldLength);
            }

            return(data);
        }
Exemplo n.º 2
0
        public static void GenerateProfile(Type type)
        {
            SerializationProfile profile = new SerializationProfile();

            FieldInfo[] fields = type.GetFields();

            int bufferOffset = 0;

            for (int i = 0; i < fields.Length; i++)
            {
                FieldInfo field = fields[i];

                Schema schema = (Schema)Attribute.GetCustomAttribute(field, typeof(Schema));

                if (schema == null)
                {
                    continue;
                }

                Type fieldType = field.FieldType;

                int memberLength = (fieldType == typeof(string)) ? schema.ManualSize : GetTypeDataLength(fieldType);

                profile.Fields.Add(new FieldMetadata {
                    FieldType        = fieldType,
                    FieldName        = field.Name,
                    FieldLength      = memberLength,
                    FieldBufferIndex = bufferOffset
                });

                bufferOffset += memberLength;
            }
            profile.BufferLength = bufferOffset;
            profiles.Add(type, profile);
        }
Exemplo n.º 3
0
        public static T Deserialize <T>(byte[] data) where T : new()
        {
            Type objType = typeof(T);

            if (!profiles.ContainsKey(objType))
            {
                GenerateProfile(objType);
            }
            SerializationProfile profile = profiles[objType];

            T Toutput = new T();

            foreach (FieldMetadata field in profile.Fields)
            {
                Type fieldType = field.FieldType;

                byte[] bdata = new byte[field.FieldLength];

                Array.Copy(data, field.FieldBufferIndex, bdata, 0, field.FieldLength);
                object val = RawDataToObject(fieldType, bdata);
                objType.GetField(field.FieldName).SetValue(Toutput, val);
                //Console.WriteLine("{0} {1}", field.FieldName, val);
            }

            return(Toutput);
        }