public static void test(bool enableCache) { SerializationMethodsBase methods = new SMAB().GetSerializationMethods(typeof(MyObject), enableCache); MyObject writeObject = new MyObject(new Vector { x = 4, y = 3, z = 5 }, "Tom", "to play in computer games", "eat testy food", "code"); writeObject.KnownWords["russian"] = new Dictionary <string, string> { { "cat", "кот" }, { "language", "язык" }, { "mouse", "мышь" }, { "code", "код" }, }; SerializeStream sstream = new SerializeStream(); methods.Serialize(sstream, writeObject); Console.WriteLine(); SerializeStream dstream = new SerializeStream(sstream.GetBytes()); MyObject readObject = ((MyObject)methods.Deserialize(dstream)); readObject.sayHello(); }
/// <summary> /// Reads the four (4) header bytes from the input stream. /// </summary> /// <param name="recordLength">The length of the record as a 16 bit unsigned integer.</param> /// <param name="recordTypeCode">The Type and Subtype codes for the current record.</param> protected virtual void ReadHeader(out ushort recordLength, out ushort recordTypeCode) { byte[] buffer = new byte[2]; // Read record length bytes into buffer SerializeStream.Read(buffer, 0, 2); recordLength = Converter.ToUInt16(buffer); // Read record type bytes into buffer SerializeStream.Read(buffer, 0, 2); recordTypeCode = (Converter.ToUInt16(buffer)); }
//--------------------------------------------------------------- #endregion //--------------------------------------------------------------- //--------------------------------------------------------------- #region Methods //--------------------------------------------------------------- /// <summary> /// Serializes the given object. /// </summary> /// <param name="obj">The object to serialize.</param> /// <param name="stream">Stream to fill with data.</param> public void Serialize(object obj, SerializeStream stream) { stream.Write("elementType", array.GetType().GetElementType()); stream.Write("length", array.Length); for (int i = 0; i < array.Length; i++) { object value = array.GetValue(i); stream.WriteAsObject(null, value); } }
/// <summary> /// Deserializes the given object. /// </summary> /// <param name="stream">Stream containing data.</param> /// <param name="type">The type of the object to create.</param> /// <returns>The deserialized object.</returns> public object Deserialize(Type type, SerializeStream stream) { Type elementType = stream.ReadType("elementType"); int length = stream.ReadInt("length"); System.Array array = System.Array.CreateInstance(elementType, length); for (int i = 0; i < array.Length; i++) { array.SetValue(stream.ReadObject(null), i); } return(array); }
/// <summary> /// Deserializes the given object. /// </summary> /// <param name="stream">Stream containing data.</param> /// <param name="type">The type of the object to create.</param> /// <returns>The deserialized object.</returns> public object Deserialize(Type type, SerializeStream stream) { int length = stream.ReadInt("registered"); for (int i = 0; i < length; i++) { stream.EnterObject(null); Register(stream.ReadString("Name"), stream.ReadString("DllPath"), stream.ReadString("ClassName")); stream.LeaveObject(); } return(this); }
protected string ReadString() { int length = SerializeStream.ReadByte(); byte[] buffer = ReadBytes(length); // special empty string handling. String of length 1 with the first character value = zero // represents null value. if (length == 1 && buffer[0] == 0) { return(null); } return(Encoding.ASCII.GetString(buffer)); }
//--------------------------------------------------------------- #endregion //--------------------------------------------------------------- //--------------------------------------------------------------- #region FactorySerializer //--------------------------------------------------------------- /// <summary> /// Serializes the given object. /// </summary> /// <param name="obj">The object to serialize.</param> /// <param name="stream">Stream to fill with data.</param> public void Serialize(object obj, SerializeStream stream) { ICollection collection = registered.Values; stream.Write("registered", collection.Count); foreach (PlugInData data in collection) { stream.EnterObject("PlugIn"); stream.Write("Name", data.Name); stream.Write("DllPath", data.DllPath); stream.Write("ClassName", data.ClassName); stream.LeaveObject(); } }
/// <summary> /// Deserializes the given object. /// </summary> /// <param name="stream">Stream containing data.</param> /// <param name="type">The type of the object to create.</param> /// <returns>The deserialized object.</returns> public object Deserialize(Type type, SerializeStream stream) { FieldInfo[] infos = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); object obj = Activator.CreateInstance(type, true); for (int i = 0; i < infos.Length; i++) { FieldInfo info = infos[i]; if (info.IsDefined(typeof(SerializeAttribute), false)) { SerializeAttribute attribute = (SerializeAttribute) info.GetCustomAttributes(typeof(SerializeAttribute), false)[0]; if (attribute.Primitive) { info.SetValue(obj, stream.Read(info.Name, info.FieldType)); } else { info.SetValue(obj, stream.ReadObject(info.Name)); } } } PropertyInfo[] pInfos = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); for (int i = 0; i < pInfos.Length; i++) { PropertyInfo pInfo = pInfos[i]; if (pInfo.IsDefined(typeof(SerializeAttribute), false)) { SerializeAttribute attribute = (SerializeAttribute) pInfo.GetCustomAttributes(typeof(SerializeAttribute), false)[0]; if (pInfo.CanWrite) { if (attribute.Primitive) { pInfo.SetValue(obj, stream.Read(pInfo.Name, pInfo.PropertyType), null); } else { pInfo.SetValue(obj, stream.ReadObject(pInfo.Name), null); } } } } return(obj); }
//--------------------------------------------------------------- #endregion //--------------------------------------------------------------- //--------------------------------------------------------------- #region ISerializer Members //--------------------------------------------------------------- /// <summary> /// Serializes the given object. /// </summary> /// <param name="obj">The object to serialize.</param> /// <param name="stream">Stream to fill with data.</param> public void Serialize(object obj, SerializeStream stream) { Type type = obj.GetType(); MemberInfo[] infos = type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); for (int i = 0; i < infos.Length; i++) { if (infos[i].IsDefined(typeof(SerializeAttribute), false)) { SerializeAttribute attribute = (SerializeAttribute) infos[i].GetCustomAttributes(typeof(SerializeAttribute), false)[0]; FieldInfo info = infos[i] as FieldInfo; PropertyInfo pInfo = infos[i] as PropertyInfo; if (info != null) { if (attribute.Primitive) { stream.Write(info.Name, info.GetValue(obj)); } else { stream.WriteAsObject(info.Name, info.GetValue(obj)); } } else if (pInfo != null && pInfo.CanRead && pInfo.CanWrite) { if (attribute.Primitive) { stream.Write(pInfo.Name, pInfo.GetValue(obj, null)); } else { stream.WriteAsObject(pInfo.Name, pInfo.GetValue(obj, null)); } } else { throw new Exception("Can't get AND set member: " + pInfo.Name); } } } }
/// <summary> /// Deserializes the given object. /// </summary> /// <param name="stream">Stream containing data.</param> /// <param name="type">The type of the object to create.</param> /// <returns>The deserialized object.</returns> public object Deserialize(Type type, SerializeStream stream) { if (type == typeof(int)) { return(stream.ReadInt("value")); } else if (type == typeof(float)) { return(stream.ReadFloat("value")); } else if (type == typeof(bool)) { return(stream.ReadBool("value")); } else { throw new NotSupportedException("Type: " + type.Name + " not supported at the moment"); } }
public SerializationMethodsBase AddTypeDependence(Type type) { SerializationMethodsBase result; if (Dependencies.TryGetValue(type, out result)) { return(result); } else { if (Serializer.GetCached(type, out result)) { } else { // Collections like types if (type.IsArray) { result = new ArraySerializationMethodsChain(type, AddTypeDependence(type.GetElementType()), false); } else if (type.GetInterfaces().Any((Type t) => SerializeStream.IsCollectionType(t))) { Type elementType = type.GetInterfaces().First((Type interfaceType) => interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(ICollection <>)).GetGenericArguments()[0]; result = (SerializationMethodsBase)typeof(CollectionSerializationMethodsChain <,>).MakeGenericType(type, elementType).GetConstructor(new Type[] { typeof(SerializationMethodsBase), typeof(bool) }).Invoke(new object[] { AddTypeDependence(elementType), false }); } else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(KeyValuePair <,>)) { Type[] genericArgs = type.GetGenericArguments(); result = (SerializationMethodsBase)typeof(KeyValuePairSerializationMethodsChain <, ,>).MakeGenericType(type, genericArgs[0], genericArgs[1]).GetConstructor(new Type[] { typeof(SerializationMethodsBase), typeof(SerializationMethodsBase), typeof(bool) }).Invoke(new object[] { AddTypeDependence(genericArgs[0]), AddTypeDependence(genericArgs[1]), false }); } else { LocalCompilationContext compileContext = new LocalCompilationContext(type, this); compileQueue.Enqueue(compileContext); result = compileContext.serializationMethods; } } } Dependencies.Add(type, result); return(result); }
//--------------------------------------------------------------- #endregion //--------------------------------------------------------------- //--------------------------------------------------------------- #region Methods //--------------------------------------------------------------- /// <summary> /// Serializes the given object. /// </summary> /// <param name="obj">The object to serialize.</param> /// <param name="stream">Stream to fill with data.</param> public void Serialize(object obj, SerializeStream stream) { Type type = obj.GetType(); if (type == typeof(int)) { stream.Write("value", (int)obj); } else if (type == typeof(float)) { stream.Write("value", (float)obj); } else if (type == typeof(bool)) { stream.Write("value", obj.ToString()); } else { throw new NotSupportedException("Type: " + type.Name + " not supported at the moment"); } }
public static void test() { Serializer.UseMethodsBuilder(new SMAB()); Friend friend = new Friend("Tom", new Friend("Bob", new Friend("Robin", new Friend("Marry")))); SerializeStream sstream = new SerializeStream(); Serializer.Serialize <Friend>(sstream, friend); Serializer.Deserialize <Friend>(new SerializeStream(sstream.GetBytes())).print(); Console.WriteLine(); Console.WriteLine($"{String.Concat(Enumerable.Repeat("-", 32).ToArray())}Cicles test{String.Concat(Enumerable.Repeat("-", 32).ToArray())}"); Friend friend1 = new Friend("VIctor", null); Friend friend2 = new Friend("Dan", friend1); friend1.friend = friend2; Friend cicleFriend = new Friend("Aurora", friend1); sstream = new SerializeStream(); Serializer.Serialize <Friend>(sstream, cicleFriend); Serializer.Deserialize <Friend>(new SerializeStream(sstream.GetBytes())).print(); }
public Formatter(SerializeStream sstream) { Stream = sstream; }
protected byte[] ReadBytes(int count) { byte[] buffer = new byte[count]; SerializeStream.Read(buffer, 0, count); return(buffer); }
/// <summary> /// Deserializes the given object. /// </summary> /// <param name="stream">Stream containing data.</param> /// <param name="type">The type of the object to create.</param> /// <returns>The deserialized object.</returns> public object Deserialize(Type type, SerializeStream stream) { int id = stream.ReadInt("id"); return(stream.ReferenceManager.GetReference(id)); }
//--------------------------------------------------------------- #endregion //--------------------------------------------------------------- //--------------------------------------------------------------- #region ISerializer Members //--------------------------------------------------------------- /// <summary> /// Serializes the given object. /// </summary> /// <param name="obj">The object to serialize.</param> /// <param name="stream">Stream to fill with data.</param> public void Serialize(object obj, SerializeStream stream) { stream.Write("id", id); }
/// <summary> /// Deserializes the given object. /// </summary> /// <param name="stream">Stream containing data.</param> /// <param name="type">The type of the object to create.</param> /// <returns>The deserialized object.</returns> public object Deserialize(Type type, SerializeStream stream) { return(stream.ReadString("value")); }
public void Compile() { if (!globalContext.EnableClassesTypes) { if (type.IsClass) { throw new ArgumentException($"Can't compile serialization functions for type {type}. To enable classes types use SMAB(enableClassesTypes = true) constructor"); } } var serializeGen = new ILGen <Action <SerializeStream, object, SerializationContext, SerializationMethodsBase[]> >(type + "_serialize", true); var deserializeGen = new ILGen <Func <SerializeStream, DeserializationContext, SerializationMethodsBase[], object> >(type + "_deserialize", true); SerializationRule typeRule = (SerializationRule)type.GetCustomAttribute(typeof(SerializationRule)); bool defaultIsSerializable = typeRule != null ? typeRule.IsSerializable : true; ILVar optimizationResult = deserializeGen.DeclareVar(typeof((bool, object))); //Context optimization if (!type.IsValueType) { serializeGen.If(serializeGen.args[2].CallMethod(OptimizeSerializationContextMethodInfo, serializeGen.args[0], serializeGen.args[1])); serializeGen.Return(); serializeGen.EndIf(); deserializeGen.Line(optimizationResult.Set(deserializeGen.args[1].CallMethod(OptimizeDeserializationContextMethodInfo, deserializeGen.args[0]))); deserializeGen.If(optimizationResult.Field(OptimizationResultItem1)); deserializeGen.Return(optimizationResult.Field(OptimizationResultItem2)); deserializeGen.EndIf(); } ILVar serializeObject = serializeGen.DeclareVar(type); ILVar deserializeObject = deserializeGen.DeclareVar(type); serializeGen.Line(serializeObject.Set(Expr.Cast(serializeGen.args[1], type))); deserializeGen.Line(deserializeObject.Set(Expr.CreateUninitialized(type))); if (!type.IsValueType) { deserializeGen.Line(deserializeGen.args[1].CallMethod(AddObjectDesreializationContextMethodInfo, deserializeObject)); } foreach (FieldInfo fieldInfo in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).OrderBy((FieldInfo fieldInfo) => fieldInfo.MetadataToken)) { SerializationRule fieldRule = (SerializationRule)fieldInfo.GetCustomAttribute(typeof(SerializationRule)); if (!(fieldRule != null ? fieldRule.IsSerializable : defaultIsSerializable)) { continue; } Type fieldType = fieldInfo.FieldType; if (SerializeStream.GetBaseTypeRWMethodsIfExists(fieldType, out RWMethodsInfo rwMethods)) { serializeGen.Line(serializeGen.args[0].CallMethod(rwMethods.writeMethodInfo, serializeObject.Field(fieldInfo))); deserializeGen.Line(deserializeObject.Field(fieldInfo).Set(deserializeGen.args[0].CallMethod(rwMethods.readMethodInfo))); } else { int fieldTypeSerializationIndex = GetTypeSerializationMethodsIndex(fieldType); serializeGen.Line(serializeGen.args[3].Index(Expr.Const(fieldTypeSerializationIndex)).CallMethod(SerializeMethodInfo, serializeGen.args[0], serializeObject.Field(fieldInfo), serializeGen.args[2])); deserializeGen.Line(deserializeObject.Field(fieldInfo).Set(Expr.Cast(deserializeGen.args[2].Index(Expr.Const(fieldTypeSerializationIndex)).CallMethod(DeserializeMethodInfo, serializeGen.args[0], serializeGen.args[1]), fieldType))); } } deserializeGen.Return(deserializeObject); serializationMethods.TypeSerializeMethod = new SerializationMethodsWithDependencies.SerializeMethod(serializeGen.compile(globalContext.WithComments)); serializationMethods.TypeDeserializeMethod = new SerializationMethodsWithDependencies.DeserializeMethod(deserializeGen.compile(globalContext.WithComments)); }
//--------------------------------------------------------------- #endregion //--------------------------------------------------------------- //--------------------------------------------------------------- #region Methods //--------------------------------------------------------------- /// <summary> /// Serializes the given object. /// </summary> /// <param name="obj">The object to serialize.</param> /// <param name="stream">Stream to fill with data.</param> public void Serialize(object obj, SerializeStream stream) { stream.Write("value", str); }
public override void Serialize(SerializeStream stream, object obj, SerializationContext context) { TypeSerializeMethod(stream, obj, context, Dependencies); }
protected bool ReadBoolean() { byte val = (byte)SerializeStream.ReadByte(); return(val == 0 ? false : true); }
public override object Deserialize(SerializeStream stream, DeserializationContext context) { return(TypeDeserializeMethod(stream, context, Dependencies)); }
protected byte ReadByte() { return((byte)SerializeStream.ReadByte()); }
protected char ReadChar() { return(Converter.ToChar(SerializeStream.ReadByte())); }
/// <summary> /// Serializes and STDF record object to the output stream. /// </summary> /// <param name="stream">Stream object to serialized the STDF data to.</param> /// <param name="obj">STDF record object to serialize.</param> public override void Serialize(Stream stream, object obj) { Buffer.SetLength(0); SerializeStream = Buffer; EndOfStream = false; EndOfRecord = false; ushort recordLength = 0; if (obj is ISTDFRecord record) { ISurrogate typeSurrogate = TypeSurrogateSelector.GetSurrogate(record.GetType()); if (typeSurrogate == null) { return; } //WriteHeader(0, record.RecordType); // long recordStartPosition = SerializeStream.Position; Type recordType = record.GetType(); SerializationInfo info = SerializationInfo.Create(recordType, Converter); typeSurrogate.GetObjectData(record, info); foreach (SerializationInfoEntry field in info) { if (field.ItemCountIndex >= 0) { // field has an item count property, so we are serializing an array. Get the number of items // to serialize from the item count field serialized earlier (we always serialize according // to the item count field rather than the array size for the array field. Normally these are // equal but it is not mandatory that they be equal). int itemCount = field.ItemCountIndex != null?info.GetValue <int>((int)field.ItemCountIndex) : 0; if (itemCount > 0) { WriteArray(field.Value, field.Type.GetElementType(), 0, itemCount); } } else { WriteMember(field.Value, field.Type); } // For optional fields, save the position after the last field written // that does not have a missing value. Per spec, we can truncate any contiguous missing // value fields from the end of the record. if (!field.IsMissingValue) { recordLength = (ushort)(SerializeStream.Position); } } //recordLength = (ushort)(lastValidPosition - recordStartPosition); if (recordLength != record.RecordLength) { throw new Exception("Mismatched record length."); } record.RecordLength = recordLength; //SerializeStream.Seek(-(SerializeStream.Position - recordStartPosition + 4), SeekOrigin.Current); SerializeStream.Flush(); SerializeStream = stream; WriteHeader(record.RecordLength, record.RecordType); // SerializeStream.Seek(record.RecordLength, SeekOrigin.Current); // SerializeStream.SetLength(SerializeStream.Position); Buffer.SetLength(recordLength); Buffer.WriteTo(stream); EndOfRecord = true; } }