From 30f3aa983b3f672a7d3d187b17fafb5a2722d3f6 Mon Sep 17 00:00:00 2001 From: Marc Hernandez Date: Fri, 12 Jul 2019 01:02:29 -0700 Subject: [PATCH] Reformat files --- Clock.cs | 10 +- Config.cs | 244 +++---- Conn.cs | 141 ++-- Helpers.cs | 12 +- Id.cs | 14 +- Log.cs | 95 +-- NetMsg.cs | 28 +- Pos.cs | 76 +- Scr.cs | 14 +- SerializableDictionary.cs | 262 +++---- Timer.cs | 620 ++++++++-------- Token.cs | 86 +-- Utilities.Interop.cs | 222 +++--- Utilities.cs | 1425 +++++++++++++++++++------------------ VersionFormatter.cs | 349 ++++----- XmlFormatter.cs | 1301 ++++++++++++++++----------------- XmlFormatter2.cs | 1091 ++++++++++++++-------------- att/CanBeNullAttribute.cs | 42 +- att/NotNullAttribute.cs | 34 +- mod/Modules.cs | 128 ++-- res/Resource.cs | 15 +- 21 files changed, 3123 insertions(+), 3086 deletions(-) diff --git a/Clock.cs b/Clock.cs index 483c567..8ce82aa 100644 --- a/Clock.cs +++ b/Clock.cs @@ -14,18 +14,18 @@ namespace lib m_lastTime = m_timer.Current; m_totalMillis = timeOffset; - m_totalSeconds= (double)m_totalMillis / 1000.0; + m_totalSeconds = (double)m_totalMillis / 1000.0; } public void tick() { long current = m_timer.Current; - m_dtMillis = (int)(current - m_lastTime); + m_dtMillis = (int)( current - m_lastTime ); m_dtSeconds = (double)m_dtMillis / 1000.0; - m_totalMillis += m_dtMillis; + m_totalMillis += m_dtMillis; m_totalSeconds = (double)m_totalMillis / 1000.0; m_lastTime = current; @@ -34,8 +34,8 @@ namespace lib public int dtMs { get { return m_dtMillis; } } public double dtSec { get { return m_dtSeconds; } } - public long ms { get { return m_totalMillis; } } - public double sec{ get { return m_totalSeconds; } } + public long ms { get { return m_totalMillis; } } + public double sec { get { return m_totalSeconds; } } Timer m_timer; diff --git a/Config.cs b/Config.cs index bce5613..6af70b3 100644 --- a/Config.cs +++ b/Config.cs @@ -6,167 +6,167 @@ using System.Reflection; namespace lib { -public class DescAttribute : Attribute -{ - public string Desc { get; private set; } - - public DescAttribute( string desc ) + public class DescAttribute : Attribute { - Desc = desc; + public string Desc { get; private set; } + + public DescAttribute( string desc ) + { + Desc = desc; + } } -} -[Serializable] -public class ConfigCfg : Config -{ - public readonly bool writeOutTemplateFiles = true; -} - - - -[Serializable] -public class Config -{ - /* - static public Config Load( string filename ) + [Serializable] + public class ConfigCfg : Config { - return null; - } - */ - - static ConfigCfg s_cfg = new ConfigCfg(); - - static public void startup( string filename ) - { - res.Mgr.register( load ); - res.Mgr.registerSub(typeof(Config)); - - s_cfg = Config.load( filename ); - + public readonly bool writeOutTemplateFiles = true; } - #region SaveLoad - /* - static public res.Ref res_load( string filename ) + + [Serializable] + public class Config { - return new res.Ref( filename, load( filename ) ); - } - */ + /* + static public Config Load( string filename ) + { + return null; + } + */ - static public T res_load( string filename ) where T : Config - { - return load( filename ); - } + static ConfigCfg s_cfg = new ConfigCfg(); - /* - static public ResRefConfig res_load( string filename, Type t ) - { - return new ResRefConfig( filename, load( filename, t ) ); - } - */ + static public void startup( string filename ) + { + res.Mgr.register( load ); + res.Mgr.registerSub( typeof( Config ) ); + + s_cfg = Config.load( filename ); + + } - static public Config load( string filename ) - { - FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read ); + #region SaveLoad + /* + static public res.Ref res_load( string filename ) + { + return new res.Ref( filename, load( filename ) ); + } + */ - XmlFormatter2 formatter = new XmlFormatter2(); + static public T res_load( string filename ) where T : Config + { + return load( filename ); + } - Config cfg = (Config)formatter.Deserialize( fs ); + /* + static public ResRefConfig res_load( string filename, Type t ) + { + return new ResRefConfig( filename, load( filename, t ) ); + } + */ - return cfg; - } - static public T load( string filename ) where T : Config - { - return (T)load( filename, typeof( T ) ); - } - - static public Config load( string filename, Type t ) - { - Config cfg = null; - - try + static public Config load( string filename ) { FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read ); XmlFormatter2 formatter = new XmlFormatter2(); - cfg = (Config)( t != null ? formatter.DeserializeKnownType( fs,t ) : formatter.Deserialize( fs ) ); + Config cfg = (Config)formatter.Deserialize( fs ); - cfg.SetFilename( filename ); + return cfg; } - catch( FileNotFoundException ) + + static public T load( string filename ) where T : Config { - Type[] types = new Type[ 0 ]; - object[] parms = new object[ 0 ]; + return (T)load( filename, typeof( T ) ); + } - //types[ 0 ] = typeof( string ); - //parms[ 0 ] = filename; - - ConstructorInfo cons = t.GetConstructor( types ); + static public Config load( string filename, Type t ) + { + Config cfg = null; try { - cfg = (Config)cons.Invoke( parms ); + FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read ); + + XmlFormatter2 formatter = new XmlFormatter2(); + + cfg = (Config)( t != null ? formatter.DeserializeKnownType( fs, t ) : formatter.Deserialize( fs ) ); + + cfg.SetFilename( filename ); } - catch( Exception e ) + catch( FileNotFoundException ) { - Log.error( $"Exception while creating config {t.ToString()}, Msg {e.Message}" ); - } + Type[] types = new Type[ 0 ]; + object[] parms = new object[ 0 ]; - //cfg.SetFilename( filename ); + //types[ 0 ] = typeof( string ); + //parms[ 0 ] = filename; - if( s_cfg.writeOutTemplateFiles ) - { - var templateFile = $"templates/{filename}"; + ConstructorInfo cons = t.GetConstructor( types ); - var dirName = Path.GetDirectoryName( templateFile ); + try + { + cfg = (Config)cons.Invoke( parms ); + } + catch( Exception e ) + { + Log.error( $"Exception while creating config {t.ToString()}, Msg {e.Message}" ); + } - lib.Util.checkAndAddDirectory( dirName ); + //cfg.SetFilename( filename ); - lib.Log.info( $"Writing out template config of type {t.Name} in {templateFile}" ); + if( s_cfg.writeOutTemplateFiles ) + { + var templateFile = $"templates/{filename}"; - Config.save( cfg, templateFile ); + var dirName = Path.GetDirectoryName( templateFile ); + + lib.Util.checkAndAddDirectory( dirName ); + + lib.Log.info( $"Writing out template config of type {t.Name} in {templateFile}" ); + + Config.save( cfg, templateFile ); } } - return cfg; + return cfg; + } + + static public void save( Config cfg ) + { + Config.save( cfg, cfg.m_filename ); + } + + static public void save( Config cfg, String filename ) + { + FileStream fs = new FileStream( filename, FileMode.Create, FileAccess.Write ); + + XmlFormatter2 formatter = new XmlFormatter2(); + + formatter.Serialize( fs, cfg ); + + fs.Close(); + } + #endregion + + private string m_filename = ""; + + public Config() + { + } + + public Config( string filename ) + { + m_filename = filename; + } + + public String Filename { get { return m_filename; } } + + protected void SetFilename( String filename ) { m_filename = filename; } + } - - static public void save( Config cfg ) - { - Config.save( cfg, cfg.m_filename ); - } - - static public void save( Config cfg, String filename ) - { - FileStream fs = new FileStream( filename, FileMode.Create, FileAccess.Write ); - - XmlFormatter2 formatter = new XmlFormatter2(); - - formatter.Serialize( fs, cfg ); - - fs.Close(); - } - #endregion - - private string m_filename = ""; - - public Config() - { - } - - public Config( string filename ) - { - m_filename = filename; - } - - public String Filename { get { return m_filename; } } - - protected void SetFilename( String filename ) { m_filename = filename; } - -} } diff --git a/Conn.cs b/Conn.cs index d45e4d4..442dac0 100644 --- a/Conn.cs +++ b/Conn.cs @@ -12,97 +12,98 @@ namespace lib -public interface IProcess -{ - void process( object obj ); -} - - - - -public class Conn -{ - public Socket Sock { get { return m_socket; } } - public Stream Stream { get { return m_streamNet; } } - - - public Conn( Socket sock, IProcess proc ) + public interface IProcess { - m_socket = sock; - - sock.NoDelay = true; - - m_streamNet = new NetworkStream( m_socket ); - - m_proc = proc; + void process( object obj ); } - public object recieveObject() + + + + public class Conn { - return recieveObject( Stream ); - } + public Socket Sock { get { return m_socket; } } + public Stream Stream { get { return m_streamNet; } } - public object recieveObject( Stream stream ) - { - object obj = null; - var formatter = new XmlFormatter2(); - - try + public Conn( Socket sock, IProcess proc ) { - obj = formatter.Deserialize( stream ); - } - catch( System.Xml.XmlException ex ) - { - lib.Log.error( $"Outer Exception {ex.Message}" ); + m_socket = sock; + + sock.NoDelay = true; + + m_streamNet = new NetworkStream( m_socket ); + + m_proc = proc; } - return obj; - } - - public void send( object obj ) - { - - var formatter = new XmlFormatter2(); - - try + public object recieveObject() { - var ms = new MemoryStream( 1024 ); - formatter.Serialize( ms, obj ); + return recieveObject( Stream ); + } + + public object recieveObject( Stream stream ) + { + object obj = null; + + var formatter = new XmlFormatter2(); + + try + { + obj = formatter.Deserialize( stream ); + } + catch( System.Xml.XmlException ex ) + { + lib.Log.error( $"Outer Exception {ex.Message}" ); + } + + return obj; + } + + public void send( object obj ) + { + + var formatter = new XmlFormatter2(); + + try + { + var ms = new MemoryStream( 1024 ); + formatter.Serialize( ms, obj ); //var str = System.Text.Encoding.Default.GetString( mm_buffer, 0, (int)ms.Position ); //lib.Log.info( $"Sent data {str} of length {ms.Position}" ); //lib.Log.info( $"Sent {obj}" ); byte[] byteSize = BitConverter.GetBytes( (uint)ms.Position ); - m_streamNet.Write( byteSize, 0, 4 ); - m_streamNet.Write( ms.GetBuffer(), 0, (int)ms.Position ); + m_streamNet.Write( byteSize, 0, 4 ); + m_streamNet.Write( ms.GetBuffer(), 0, (int)ms.Position ); - m_streamNet.Flush(); + m_streamNet.Flush(); + } + catch( Exception e ) + { + lib.Log.warn( $"Exception sending obj {obj} of {e}" ); + throw; + } } - catch( Exception e ) + + public virtual void recieve( object obj ) { - lib.Log.warn( $"Exception sending obj {obj} of {e}" ); - throw; + if( m_proc != null ) + m_proc.process( obj ); } + + Socket m_socket; + + NetworkStream m_streamNet; + + IProcess m_proc; + + + + //private BufferedStream m_streamBufIn; + //private BufferedStream m_streamBufOut; } - - public virtual void recieve( object obj ) - { - if( m_proc != null ) m_proc.process( obj ); - } - - Socket m_socket; - - NetworkStream m_streamNet; - - IProcess m_proc; - - - - //private BufferedStream m_streamBufIn; - //private BufferedStream m_streamBufOut; -} diff --git a/Helpers.cs b/Helpers.cs index 37f2009..cb448ac 100644 --- a/Helpers.cs +++ b/Helpers.cs @@ -80,8 +80,8 @@ namespace lib Type[] types = dict.GetType().GetGenericArguments(); - xmlWriter.WriteAttributeString( "keyType", types[ 0 ].FullName ); - xmlWriter.WriteAttributeString( "valType", types[ 1 ].FullName ); + xmlWriter.WriteAttributeString( "keyType", types[0].FullName ); + xmlWriter.WriteAttributeString( "valType", types[1].FullName ); foreach( KeyValuePair kvp in dict ) { @@ -135,15 +135,15 @@ namespace lib { if( node.Attributes != null ) { - args[ 0 ] = node.GetAttribute( "key" ); + args[0] = node.GetAttribute( "key" ); TKey key = (TKey)keyMI.Invoke( null, args ); - args[ 0 ] = node.GetAttribute( "value" ); + args[0] = node.GetAttribute( "value" ); TVal val = (TVal)valMI.Invoke( null, args ); - dict[ key ] = val; + dict[key] = val; } else { @@ -162,7 +162,7 @@ namespace lib Log.error( String.Format( $"Key type conversion not found for type {keyType}" ) ); if( valMI == null ) - Log.error( String.Format( $"Val type conversion not found for type {valType}" ) ); + Log.error( String.Format( $"Val type conversion not found for type {valType}" ) ); } } diff --git a/Id.cs b/Id.cs index 36a5292..5954041 100644 --- a/Id.cs +++ b/Id.cs @@ -85,7 +85,7 @@ namespace lib { return m_value == obj; } - + public override int GetHashCode() { return (int)m_value ^ (int)( m_value >> 32 ); @@ -197,7 +197,7 @@ namespace lib // T:System.OverflowException: // The s parameter represents a number less than System.UInt64.MinValue or greater // than System.UInt64.MaxValue. - + public static ulong Parse( string s ) { @@ -237,7 +237,7 @@ namespace lib // T:System.OverflowException: // The s parameter represents a number less than System.UInt64.MinValue or greater // than System.UInt64.MaxValue. -or-s includes non-zero, fractional digits. - + public static ulong Parse( string s, NumberStyles style ) { @@ -269,7 +269,7 @@ namespace lib // T:System.OverflowException: // The s parameter represents a number less than System.UInt64.MinValue or greater // than System.UInt64.MaxValue. - + public static ulong Parse( string s, IFormatProvider provider ) { @@ -311,7 +311,7 @@ namespace lib // T:System.OverflowException: // The s parameter represents a number less than System.UInt64.MinValue or greater // than System.UInt64.MaxValue. -or-s includes non-zero, fractional digits. - + public static ulong Parse( string s, NumberStyles style, IFormatProvider provider ) { @@ -337,7 +337,7 @@ namespace lib // // Returns: // true if s was converted successfully; otherwise, false. - + public static bool TryParse( string s, out ulong result ) { @@ -377,7 +377,7 @@ namespace lib // /// style is not a System.Globalization.NumberStyles value. -or-style is not // a combination of System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber // values. - + public static bool TryParse( string s, NumberStyles style, IFormatProvider provider, out ulong result ) { diff --git a/Log.cs b/Log.cs index cc1013e..67ef964 100644 --- a/Log.cs +++ b/Log.cs @@ -15,26 +15,26 @@ namespace lib [Flags] public enum LogTypeNew { - Invalid = 0, + Invalid = 0, // Frequency - FrequencyBase = 1, - FrequencyBits = 2, - FrequencyMask = ( ( 1 << FrequencyBits ) - 1 ) << FrequencyBase, + FrequencyBase = 1, + FrequencyBits = 2, + FrequencyMask = ( ( 1 << FrequencyBits ) - 1 ) << FrequencyBase, - Detail = 0b01 << FrequencyBase, - Normal = 0b10 << FrequencyBase, - Overview = 0b11 << FrequencyBase, + Detail = 0b01 << FrequencyBase, + Normal = 0b10 << FrequencyBase, + Overview = 0b11 << FrequencyBase, // Type TypeBase = FrequencyBase + FrequencyBits, TypeBits = 3, TypeMask = ( ( 1 << TypeBits ) - 1 ) << TypeBase, - Startup = 0b001 << TypeBase, - Running = 0b010 << TypeBase, - Shutdown= 0b011 << TypeBase, - Error = 0b101 << TypeBase, + Startup = 0b001 << TypeBase, + Running = 0b010 << TypeBase, + Shutdown = 0b011 << TypeBase, + Error = 0b101 << TypeBase, } @@ -42,22 +42,22 @@ namespace lib [Flags] public enum LogType { - Invalid = 0, - Trace = 1, - Debug = 2, - Info = 3, - Warn = 4, - Error = 5, - Fatal = 6, + Invalid = 0, + Trace = 1, + Debug = 2, + Info = 3, + Warn = 4, + Error = 5, + Fatal = 6, } public struct LogEvent { public DateTime Time; - public LogType LogType; - public string Cat; - public string Msg; - public object Obj; + public LogType LogType; + public string Cat; + public string Msg; + public object Obj; public LogEvent( LogType logType, string cat, string msg, object obj ) { @@ -72,7 +72,7 @@ namespace lib public delegate void Log_delegate( LogEvent evt ); - public class Log : TraceListener + public class Log : TraceListener { static public void create( string filename ) { @@ -107,32 +107,32 @@ namespace lib // Forwards. static public void fatal( string msg, string cat = "unk", object obj = null ) { - log(msg, LogType.Fatal, cat, obj); + log( msg, LogType.Fatal, cat, obj ); } static public void error( string msg, string cat = "unk", object obj = null ) { - log(msg, LogType.Error, cat, obj); + log( msg, LogType.Error, cat, obj ); } - static public void warn( string msg, string cat = "unk", object obj = null ) + static public void warn( string msg, string cat = "unk", object obj = null ) { log( msg, LogType.Warn, cat, obj ); } static public void info( string msg, string cat = "unk", object obj = null ) { - log(msg, LogType.Info, cat, obj); + log( msg, LogType.Info, cat, obj ); } static public void debug( string msg, string cat = "unk", object obj = null ) { - log(msg, LogType.Debug, cat, obj); + log( msg, LogType.Debug, cat, obj ); } static public void trace( string msg, string cat = "unk", object obj = null ) { - log(msg, LogType.Trace, cat, obj); + log( msg, LogType.Trace, cat, obj ); } static public void log( string msg, LogType type = LogType.Debug, string cat = "unk", object obj = null ) @@ -146,7 +146,7 @@ namespace lib } - static public void logProps( object obj, string header, LogType type = LogType.Debug, string cat = "unk" ) + static public void logProps( object obj, string header, LogType type = LogType.Debug, string cat = "unk" ) { var list = scr.GetAllProperties( obj.GetType() ); @@ -175,7 +175,7 @@ namespace lib } //This might seem a little odd, but the intent is that usually you wont need to set notExpectedValue. - static public void expected( T value, string falseString, string trueString = "", T notExpectedValue = default(T) ) + static public void expected( T value, string falseString, string trueString = "", T notExpectedValue = default( T ) ) { if( !value.Equals( notExpectedValue ) ) @@ -196,10 +196,10 @@ namespace lib m_stream = new FileStream( filename, FileMode.Append, FileAccess.Write ); m_writer = new StreamWriter( m_stream ); - + m_errorStream = new FileStream( filename + ".error", FileMode.Append, FileAccess.Write ); m_errorWriter = new StreamWriter( m_errorStream ); - + Debug.Listeners.Add( this ); string msg = "\n==============================================================================\nLogfile " + filename + " startup at " + DateTime.Now.ToString(); @@ -213,7 +213,7 @@ namespace lib { WriteLine( msg ); } - + public override void WriteLine( string msg ) { error( msg ); @@ -278,7 +278,8 @@ namespace lib return '*'; case LogType.Fatal: return '*'; - default: return '?'; + default: + return '?'; } } @@ -376,22 +377,22 @@ namespace lib //} ); } */ - + private Stream m_stream; private StreamWriter m_writer; - + private Stream m_errorStream; private StreamWriter m_errorWriter; - + private ArrayList m_delegates = new ArrayList(); } - - - - - - - - - + + + + + + + + + } diff --git a/NetMsg.cs b/NetMsg.cs index 582e36e..5e77ecb 100644 --- a/NetMsg.cs +++ b/NetMsg.cs @@ -18,7 +18,7 @@ namespace lib.Net m_username = name; m_password = pass; } - + public readonly String m_username; public readonly String m_password; } @@ -30,7 +30,7 @@ namespace lib.Net { m_resp = resp; } - + public readonly bool m_resp; } @@ -39,13 +39,13 @@ namespace lib.Net [Serializable] public class Admin { - + }; [Serializable] public class CreateEntity : Admin { - + } @@ -54,7 +54,7 @@ namespace lib.Net { } - #endregion + #endregion [Serializable] public class EntityBase @@ -63,7 +63,7 @@ namespace lib.Net { m_id = id; } - + public readonly int m_id; }; @@ -78,7 +78,7 @@ namespace lib.Net m_y = y; m_z = z; } - + public readonly float m_x; public readonly float m_y; public readonly float m_z; @@ -91,13 +91,13 @@ namespace lib.Net base( id ) { } - + //Should an entity have a mesh? Be made up of multiple meshes? - public readonly String m_mesh; + public readonly String m_mesh; } - - - - - + + + + + } diff --git a/Pos.cs b/Pos.cs index 5303b84..a97c97d 100644 --- a/Pos.cs +++ b/Pos.cs @@ -3,50 +3,50 @@ using System; namespace lib { -[Serializable] -public struct Pos -{ - public float x { get; private set; } - public float y { get; private set; } - public float z { get; private set; } + [Serializable] + public struct Pos + { + public float x { get; private set; } + public float y { get; private set; } + public float z { get; private set; } - public Pos( float _x, float _y, float _z ) : this() - { - x = _x; - y = _y; - z = _z; - } + public Pos( float _x, float _y, float _z ) : this() + { + x = _x; + y = _y; + z = _z; + } - // overload operator + - public static Pos operator +( Pos a, Pos b ) - { - return new Pos( a.x + b.x, a.y + b.y, a.z + b.z ); - } + // overload operator + + public static Pos operator +( Pos a, Pos b ) + { + return new Pos( a.x + b.x, a.y + b.y, a.z + b.z ); + } - public static Pos operator -( Pos a, Pos b ) - { - return new Pos( a.x - b.x, a.y - b.y, a.z - b.z ); - } + public static Pos operator -( Pos a, Pos b ) + { + return new Pos( a.x - b.x, a.y - b.y, a.z - b.z ); + } - public static Pos operator /( Pos a, float val ) - { - return new Pos( a.x / val, a.y / val, a.z / val ); - } - - public static Pos operator *( Pos a, float val ) - { - return new Pos( a.x * val, a.y * val, a.z * val ); - } + public static Pos operator /( Pos a, float val ) + { + return new Pos( a.x / val, a.y / val, a.z / val ); + } - public float distSqr( Pos other ) - { - float dx = x - other.x; - float dy = y - other.y; - float dz = z - other.z; - - return dx * dx + dy * dy + dz * dz; + public static Pos operator *( Pos a, float val ) + { + return new Pos( a.x * val, a.y * val, a.z * val ); + } + + public float distSqr( Pos other ) + { + float dx = x - other.x; + float dy = y - other.y; + float dz = z - other.z; + + return dx * dx + dy * dy + dz * dz; + } } -} } diff --git a/Scr.cs b/Scr.cs index 3d477ed..4ef52cc 100644 --- a/Scr.cs +++ b/Scr.cs @@ -48,11 +48,12 @@ static public class scr { var success = m_en.MoveNext(); - if( !success ) return false; + if( !success ) + return false; - while( !m_pred( m_en.Current ) && (success = m_en.MoveNext()) ) + while( !m_pred( m_en.Current ) && ( success = m_en.MoveNext() ) ) { - + } return success; @@ -99,8 +100,8 @@ static public class scr } #endregion - IEnumerator m_en; - Predicate m_pred; + IEnumerator m_en; + Predicate m_pred; } @@ -181,7 +182,8 @@ static public class scr public static ImmutableList GetAllProperties( Type t ) { - if( s_propCache.TryGetValue( t, out var info ) ) return info; + if( s_propCache.TryGetValue( t, out var info ) ) + return info; var list = new List(); diff --git a/SerializableDictionary.cs b/SerializableDictionary.cs index c467c7d..229453d 100644 --- a/SerializableDictionary.cs +++ b/SerializableDictionary.cs @@ -10,148 +10,156 @@ using System.Security.Permissions; namespace lib { - [Serializable] - public class SerializableDictionary : Dictionary, IXmlSerializable, ISerializable - { - #region Constants - private const string DictionaryNodeName = "Dictionary"; - private const string ItemNodeName = "Item"; - private const string KeyNodeName = "Key"; - private const string ValueNodeName = "Value"; - #endregion - #region Constructors - public SerializableDictionary() - { - } + [Serializable] + public class SerializableDictionary : Dictionary, IXmlSerializable, ISerializable + { + #region Constants + private const string DictionaryNodeName = "Dictionary"; + private const string ItemNodeName = "Item"; + private const string KeyNodeName = "Key"; + private const string ValueNodeName = "Value"; + #endregion + #region Constructors + public SerializableDictionary() + { + } - public SerializableDictionary(IDictionary dictionary) - : base(dictionary) - { - } + public SerializableDictionary( IDictionary dictionary ) + : base( dictionary ) + { + } - public SerializableDictionary(IEqualityComparer comparer) - : base(comparer) - { - } + public SerializableDictionary( IEqualityComparer comparer ) + : base( comparer ) + { + } - public SerializableDictionary(int capacity) - : base(capacity) - { - } + public SerializableDictionary( int capacity ) + : base( capacity ) + { + } - public SerializableDictionary(IDictionary dictionary, IEqualityComparer comparer) - : base(dictionary, comparer) - { - } + public SerializableDictionary( IDictionary dictionary, IEqualityComparer comparer ) + : base( dictionary, comparer ) + { + } - public SerializableDictionary(int capacity, IEqualityComparer comparer) - : base(capacity, comparer) - { - } + public SerializableDictionary( int capacity, IEqualityComparer comparer ) + : base( capacity, comparer ) + { + } - #endregion - #region ISerializable Members + #endregion + #region ISerializable Members - protected SerializableDictionary(SerializationInfo info, StreamingContext context) - { - int itemCount = info.GetInt32("ItemCount"); - for (int i = 0; i < itemCount; i++) { - KeyValuePair kvp = (KeyValuePair)info.GetValue(String.Format( $"Item{i}" ), typeof(KeyValuePair)); - this.Add(kvp.Key, kvp.Value); - } - } + protected SerializableDictionary( SerializationInfo info, StreamingContext context ) + { + int itemCount = info.GetInt32("ItemCount"); + for( int i = 0; i < itemCount; i++ ) + { + KeyValuePair kvp = (KeyValuePair)info.GetValue(String.Format( $"Item{i}" ), typeof(KeyValuePair)); + this.Add( kvp.Key, kvp.Value ); + } + } - [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("ItemCount", this.Count); - int itemIdx = 0; - foreach (KeyValuePair kvp in this) { - info.AddValue(String.Format( $"Item{itemIdx}" ), kvp, typeof(KeyValuePair)); - itemIdx++; - } - } + [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] + void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context ) + { + info.AddValue( "ItemCount", this.Count ); + int itemIdx = 0; + foreach( KeyValuePair kvp in this ) + { + info.AddValue( String.Format( $"Item{itemIdx}" ), kvp, typeof( KeyValuePair ) ); + itemIdx++; + } + } - #endregion - #region IXmlSerializable Members + #endregion + #region IXmlSerializable Members - void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) - { - //writer.WriteStartElement(DictionaryNodeName); - foreach (KeyValuePair kvp in this) { - writer.WriteStartElement(ItemNodeName); - writer.WriteStartElement(KeyNodeName); - KeySerializer.Serialize(writer, kvp.Key); - writer.WriteEndElement(); - writer.WriteStartElement(ValueNodeName); - ValueSerializer.Serialize(writer, kvp.Value); - writer.WriteEndElement(); - writer.WriteEndElement(); - } - //writer.WriteEndElement(); - } + void IXmlSerializable.WriteXml( System.Xml.XmlWriter writer ) + { + //writer.WriteStartElement(DictionaryNodeName); + foreach( KeyValuePair kvp in this ) + { + writer.WriteStartElement( ItemNodeName ); + writer.WriteStartElement( KeyNodeName ); + KeySerializer.Serialize( writer, kvp.Key ); + writer.WriteEndElement(); + writer.WriteStartElement( ValueNodeName ); + ValueSerializer.Serialize( writer, kvp.Value ); + writer.WriteEndElement(); + writer.WriteEndElement(); + } + //writer.WriteEndElement(); + } - void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) - { - if (reader.IsEmptyElement) { - return; - } + void IXmlSerializable.ReadXml( System.Xml.XmlReader reader ) + { + if( reader.IsEmptyElement ) + { + return; + } - // Move past container - if (!reader.Read()){ - throw new XmlException("Error in Deserialization of Dictionary"); - } + // Move past container + if( !reader.Read() ) + { + throw new XmlException( "Error in Deserialization of Dictionary" ); + } - //reader.ReadStartElement(DictionaryNodeName); - while (reader.NodeType != XmlNodeType.EndElement) { - reader.ReadStartElement(ItemNodeName); - reader.ReadStartElement(KeyNodeName); - TKey key = (TKey)KeySerializer.Deserialize(reader); - reader.ReadEndElement(); - reader.ReadStartElement(ValueNodeName); - TVal value = (TVal)ValueSerializer.Deserialize(reader); - reader.ReadEndElement(); - reader.ReadEndElement(); - this.Add(key, value); - reader.MoveToContent(); - } - //reader.ReadEndElement(); + //reader.ReadStartElement(DictionaryNodeName); + while( reader.NodeType != XmlNodeType.EndElement ) + { + reader.ReadStartElement( ItemNodeName ); + reader.ReadStartElement( KeyNodeName ); + TKey key = (TKey)KeySerializer.Deserialize(reader); + reader.ReadEndElement(); + reader.ReadStartElement( ValueNodeName ); + TVal value = (TVal)ValueSerializer.Deserialize(reader); + reader.ReadEndElement(); + reader.ReadEndElement(); + this.Add( key, value ); + reader.MoveToContent(); + } + //reader.ReadEndElement(); - reader.ReadEndElement(); // Read End Element to close Read of containing node - } + reader.ReadEndElement(); // Read End Element to close Read of containing node + } - System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() - { - return null; - } + System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() + { + return null; + } - #endregion - #region Private Properties - protected XmlSerializer ValueSerializer - { - get - { - if (valueSerializer == null) { - valueSerializer = new XmlSerializer(typeof(TVal)); - } - return valueSerializer; - } - } + #endregion + #region Private Properties + protected XmlSerializer ValueSerializer + { + get + { + if( valueSerializer == null ) + { + valueSerializer = new XmlSerializer( typeof( TVal ) ); + } + return valueSerializer; + } + } - private XmlSerializer KeySerializer - { - get - { - if (keySerializer == null) { - keySerializer = new XmlSerializer(typeof(TKey)); - } - return keySerializer; - } - } - #endregion - #region Private Members - private XmlSerializer keySerializer = null; - private XmlSerializer valueSerializer = null; - #endregion - } + private XmlSerializer KeySerializer + { + get + { + if( keySerializer == null ) + { + keySerializer = new XmlSerializer( typeof( TKey ) ); + } + return keySerializer; + } + } + #endregion + #region Private Members + private XmlSerializer keySerializer = null; + private XmlSerializer valueSerializer = null; + #endregion + } } diff --git a/Timer.cs b/Timer.cs index b5824b7..0c6ee33 100644 --- a/Timer.cs +++ b/Timer.cs @@ -6,336 +6,336 @@ using System.Threading; namespace lib { - public class MicroStopwatch : System.Diagnostics.Stopwatch - { - readonly double _microSecPerTick - = 1000000D / System.Diagnostics.Stopwatch.Frequency; + public class MicroStopwatch : System.Diagnostics.Stopwatch + { + readonly double _microSecPerTick + = 1000000D / System.Diagnostics.Stopwatch.Frequency; - public MicroStopwatch() - { - if (!System.Diagnostics.Stopwatch.IsHighResolution) - { - throw new Exception("On this system the high-resolution " + - "performance counter is not available"); - } - } - - public long ElapsedMicroseconds - { - get - { - return (long)(ElapsedTicks * _microSecPerTick); - } - } - } - - /// - /// MicroTimer class - /// - public class MicroTimer - { - public delegate void MicroTimerElapsedEventHandler( - object sender, - MicroTimerEventArgs timerEventArgs); - public event MicroTimerElapsedEventHandler MicroTimerElapsed; - - System.Threading.Thread _threadTimer = null; - long _ignoreEventIfLateBy = long.MaxValue; - long _timerIntervalInMicroSec = 0; - bool _stopTimer = true; - - public MicroTimer() - { - } - - public MicroTimer(long timerIntervalInMicroseconds) - { - Interval = timerIntervalInMicroseconds; - } - - public long Interval - { - get - { - return System.Threading.Interlocked.Read( - ref _timerIntervalInMicroSec); - } - set - { - System.Threading.Interlocked.Exchange( - ref _timerIntervalInMicroSec, value); - } - } - - public long IgnoreEventIfLateBy - { - get - { - return System.Threading.Interlocked.Read( - ref _ignoreEventIfLateBy); - } - set - { - System.Threading.Interlocked.Exchange( - ref _ignoreEventIfLateBy, value <= 0 ? long.MaxValue : value); - } - } - - public bool Enabled - { - set - { - if (value) - { - Start(); - } - else - { - Stop(); - } - } - get - { - return (_threadTimer != null && _threadTimer.IsAlive); - } - } - - public void Start() - { - if (Enabled || Interval <= 0) - { - return; - } - - _stopTimer = false; - - System.Threading.ThreadStart threadStart = delegate() - { - NotificationTimer(ref _timerIntervalInMicroSec, - ref _ignoreEventIfLateBy, - ref _stopTimer); - }; - - _threadTimer = new System.Threading.Thread(threadStart); - _threadTimer.Priority = System.Threading.ThreadPriority.Highest; - _threadTimer.Start(); - } - - public void Stop() - { - _stopTimer = true; - - if (_threadTimer != null && _threadTimer.ManagedThreadId == - System.Threading.Thread.CurrentThread.ManagedThreadId) - { - return; - } - - while (Enabled) - { - System.Threading.Thread.SpinWait(10); - } - } - - void NotificationTimer(ref long timerIntervalInMicroSec, - ref long ignoreEventIfLateBy, - ref bool stopTimer) - { - int timerCount = 0; - long nextNotification = 0; - - MicroStopwatch microStopwatch = new MicroStopwatch(); - microStopwatch.Start(); - - while (!stopTimer) - { - long callbackFunctionExecutionTime = - microStopwatch.ElapsedMicroseconds - nextNotification; - - long timerIntervalInMicroSecCurrent = - System.Threading.Interlocked.Read(ref timerIntervalInMicroSec); - long ignoreEventIfLateByCurrent = - System.Threading.Interlocked.Read(ref ignoreEventIfLateBy); - - nextNotification += timerIntervalInMicroSecCurrent; - timerCount++; - long elapsedMicroseconds = 0; - - while ( (elapsedMicroseconds = microStopwatch.ElapsedMicroseconds) - < nextNotification) - { - System.Threading.Thread.SpinWait(10); - } - - long timerLateBy = elapsedMicroseconds - nextNotification; - - if (timerLateBy >= ignoreEventIfLateByCurrent) - { - continue; - } - - MicroTimerEventArgs microTimerEventArgs = - new MicroTimerEventArgs(timerCount, - elapsedMicroseconds, - timerLateBy, - callbackFunctionExecutionTime); - MicroTimerElapsed(this, microTimerEventArgs); - } - - microStopwatch.Stop(); - } - } - - /// - /// MicroTimer Event Argument class - /// - public class MicroTimerEventArgs : EventArgs - { - // Simple counter, number times timed event (callback function) executed - public int TimerCount { get; private set; } - - // Time when timed event was called since timer started - public long ElapsedMicroseconds { get; private set; } - - // How late the timer was compared to when it should have been called - public long TimerLateBy { get; private set; } - - // Time it took to execute previous call to callback function (OnTimedEvent) - public long CallbackFunctionExecutionTime { get; private set; } - - public MicroTimerEventArgs(int timerCount, - long elapsedMicroseconds, - long timerLateBy, - long callbackFunctionExecutionTime) - { - TimerCount = timerCount; - ElapsedMicroseconds = elapsedMicroseconds; - TimerLateBy = timerLateBy; - CallbackFunctionExecutionTime = callbackFunctionExecutionTime; - } - } - - - public class Timer + public MicroStopwatch() { - MicroStopwatch m_watch; - private long startTime; - private long stopTime; - private long freq; - private long freq_millis; - - public Timer() + if( !System.Diagnostics.Stopwatch.IsHighResolution ) { - m_watch = new MicroStopwatch(); - //startTime = m_watch.ElapsedMicroseconds; - //stopTime = m_watch.ElapsedMicroseconds; - freq = 1000 * 1000; - freq_millis = freq / 1000; - - Start(); - } - - // Start the timer - - public Timer Start() - { - m_watch.Start(); - startTime = m_watch.ElapsedMicroseconds; - stopTime = m_watch.ElapsedMicroseconds; - return this; - } - - // Stop the timer - - public Timer Stop() - { - m_watch.Stop(); - stopTime = m_watch.ElapsedMicroseconds; - return this; - } - - public double Seconds - { - get - { - long current = m_watch.ElapsedMicroseconds; - return (double)( current - startTime ) / freq; - } - } - - public long Current - { - get - { - long current = m_watch.ElapsedMicroseconds; - return ( current - startTime ) / freq_millis; - } - } - - public double Duration - { - get - { - return (double)( stopTime - startTime ) / (double)freq; - } - } - - public long DurationMS - { - get { return ( stopTime - startTime ) / freq_millis; } + throw new Exception( "On this system the high-resolution " + + "performance counter is not available" ); } } + public long ElapsedMicroseconds + { + get + { + return (long)( ElapsedTicks * _microSecPerTick ); + } + } + } + + /// + /// MicroTimer class + /// + public class MicroTimer + { + public delegate void MicroTimerElapsedEventHandler( + object sender, + MicroTimerEventArgs timerEventArgs ); + public event MicroTimerElapsedEventHandler MicroTimerElapsed; + + System.Threading.Thread _threadTimer = null; + long _ignoreEventIfLateBy = long.MaxValue; + long _timerIntervalInMicroSec = 0; + bool _stopTimer = true; + + public MicroTimer() + { + } + + public MicroTimer( long timerIntervalInMicroseconds ) + { + Interval = timerIntervalInMicroseconds; + } + + public long Interval + { + get + { + return System.Threading.Interlocked.Read( + ref _timerIntervalInMicroSec ); + } + set + { + System.Threading.Interlocked.Exchange( + ref _timerIntervalInMicroSec, value ); + } + } + + public long IgnoreEventIfLateBy + { + get + { + return System.Threading.Interlocked.Read( + ref _ignoreEventIfLateBy ); + } + set + { + System.Threading.Interlocked.Exchange( + ref _ignoreEventIfLateBy, value <= 0 ? long.MaxValue : value ); + } + } + + public bool Enabled + { + set + { + if( value ) + { + Start(); + } + else + { + Stop(); + } + } + get + { + return ( _threadTimer != null && _threadTimer.IsAlive ); + } + } + + public void Start() + { + if( Enabled || Interval <= 0 ) + { + return; + } + + _stopTimer = false; + + System.Threading.ThreadStart threadStart = delegate() + { + NotificationTimer(ref _timerIntervalInMicroSec, + ref _ignoreEventIfLateBy, + ref _stopTimer); + }; + + _threadTimer = new System.Threading.Thread( threadStart ); + _threadTimer.Priority = System.Threading.ThreadPriority.Highest; + _threadTimer.Start(); + } + + public void Stop() + { + _stopTimer = true; + + if( _threadTimer != null && _threadTimer.ManagedThreadId == + System.Threading.Thread.CurrentThread.ManagedThreadId ) + { + return; + } + + while( Enabled ) + { + System.Threading.Thread.SpinWait( 10 ); + } + } + + void NotificationTimer( ref long timerIntervalInMicroSec, + ref long ignoreEventIfLateBy, + ref bool stopTimer ) + { + int timerCount = 0; + long nextNotification = 0; + + MicroStopwatch microStopwatch = new MicroStopwatch(); + microStopwatch.Start(); + + while( !stopTimer ) + { + long callbackFunctionExecutionTime = + microStopwatch.ElapsedMicroseconds - nextNotification; + + long timerIntervalInMicroSecCurrent = + System.Threading.Interlocked.Read(ref timerIntervalInMicroSec); + long ignoreEventIfLateByCurrent = + System.Threading.Interlocked.Read(ref ignoreEventIfLateBy); + + nextNotification += timerIntervalInMicroSecCurrent; + timerCount++; + long elapsedMicroseconds = 0; + + while( ( elapsedMicroseconds = microStopwatch.ElapsedMicroseconds ) + < nextNotification ) + { + System.Threading.Thread.SpinWait( 10 ); + } + + long timerLateBy = elapsedMicroseconds - nextNotification; + + if( timerLateBy >= ignoreEventIfLateByCurrent ) + { + continue; + } + + MicroTimerEventArgs microTimerEventArgs = + new MicroTimerEventArgs(timerCount, + elapsedMicroseconds, + timerLateBy, + callbackFunctionExecutionTime); + MicroTimerElapsed( this, microTimerEventArgs ); + } + + microStopwatch.Stop(); + } + } + + /// + /// MicroTimer Event Argument class + /// + public class MicroTimerEventArgs : EventArgs + { + // Simple counter, number times timed event (callback function) executed + public int TimerCount { get; private set; } + + // Time when timed event was called since timer started + public long ElapsedMicroseconds { get; private set; } + + // How late the timer was compared to when it should have been called + public long TimerLateBy { get; private set; } + + // Time it took to execute previous call to callback function (OnTimedEvent) + public long CallbackFunctionExecutionTime { get; private set; } + + public MicroTimerEventArgs( int timerCount, + long elapsedMicroseconds, + long timerLateBy, + long callbackFunctionExecutionTime ) + { + TimerCount = timerCount; + ElapsedMicroseconds = elapsedMicroseconds; + TimerLateBy = timerLateBy; + CallbackFunctionExecutionTime = callbackFunctionExecutionTime; + } + } + + + public class Timer + { + MicroStopwatch m_watch; + private long startTime; + private long stopTime; + private long freq; + private long freq_millis; + + public Timer() + { + m_watch = new MicroStopwatch(); + //startTime = m_watch.ElapsedMicroseconds; + //stopTime = m_watch.ElapsedMicroseconds; + freq = 1000 * 1000; + freq_millis = freq / 1000; + + Start(); + } + + // Start the timer + + public Timer Start() + { + m_watch.Start(); + startTime = m_watch.ElapsedMicroseconds; + stopTime = m_watch.ElapsedMicroseconds; + return this; + } + + // Stop the timer + + public Timer Stop() + { + m_watch.Stop(); + stopTime = m_watch.ElapsedMicroseconds; + return this; + } + + public double Seconds + { + get + { + long current = m_watch.ElapsedMicroseconds; + return (double)( current - startTime ) / freq; + } + } + + public long Current + { + get + { + long current = m_watch.ElapsedMicroseconds; + return ( current - startTime ) / freq_millis; + } + } + + public double Duration + { + get + { + return (double)( stopTime - startTime ) / (double)freq; + } + } + + public long DurationMS + { + get { return ( stopTime - startTime ) / freq_millis; } + } + } + public class TimerWin { - [DllImport("Kernel32.dll")] - private static extern bool QueryPerformanceCounter( - out long lpPerformanceCount); + [DllImport( "Kernel32.dll" )] + private static extern bool QueryPerformanceCounter( + out long lpPerformanceCount ); - [DllImport("Kernel32.dll")] - private static extern bool QueryPerformanceFrequency( - out long lpFrequency); + [DllImport( "Kernel32.dll" )] + private static extern bool QueryPerformanceFrequency( + out long lpFrequency ); - private long startTime; - private long stopTime; - private long freq; - private long freq_millis; + private long startTime; + private long stopTime; + private long freq; + private long freq_millis; - // Constructor + // Constructor - public TimerWin() - { - startTime = 0; - stopTime = 0; + public TimerWin() + { + startTime = 0; + stopTime = 0; - if (QueryPerformanceFrequency(out freq) == false) - { - // high-performance counter not supported - throw new Win32Exception(); - } + if( QueryPerformanceFrequency( out freq ) == false ) + { + // high-performance counter not supported + throw new Win32Exception(); + } - freq_millis = freq / 1000; + freq_millis = freq / 1000; - } + } - // Start the timer + // Start the timer - public void Start() - { - // lets do the waiting threads there work + public void Start() + { + // lets do the waiting threads there work - //Thread.Sleep(0); + //Thread.Sleep(0); - QueryPerformanceCounter(out startTime); - } + QueryPerformanceCounter( out startTime ); + } - // Stop the timer + // Stop the timer - public void Stop() - { - QueryPerformanceCounter(out stopTime); - } + public void Stop() + { + QueryPerformanceCounter( out stopTime ); + } public double Seconds { @@ -368,10 +368,10 @@ namespace lib return (double)( stopTime - startTime ) / (double)freq; } } - + public long DurationMS { - get { return (stopTime - startTime) / freq_millis; } + get { return ( stopTime - startTime ) / freq_millis; } } } } diff --git a/Token.cs b/Token.cs index 9525ed2..8a5a915 100644 --- a/Token.cs +++ b/Token.cs @@ -4,51 +4,51 @@ using System.Diagnostics; namespace lib { -//TODO PERF fix this and make it fast. + //TODO PERF fix this and make it fast. -[Serializable] -public struct Token -{ - public string str { get{ return m_str; } } - - public Token( String str ) + [Serializable] + public struct Token { - m_str = str; - m_hash = m_str.GetHashCode(); + public string str { get { return m_str; } } + + public Token( String str ) + { + m_str = str; + m_hash = m_str.GetHashCode(); + } + + public override bool Equals( object obj ) + { + if( !( obj is Token ) ) + return false; + + //This doesnt use as because Token is a struct + var otherId = (Token)obj; + + if( m_hash != otherId.m_hash ) + return false; + + return m_str == otherId.m_str; + } + + + public bool Equals_fast( Token other ) + { + return m_hash == other.m_hash && m_str == other.m_str; + } + + public override int GetHashCode() + { + return m_hash; + } + + public override string ToString() + { + return m_str; + } + + int m_hash; + String m_str; } - public override bool Equals( object obj ) - { - if( !( obj is Token ) ) - return false; - - //This doesnt use as because Token is a struct - var otherId = (Token)obj; - - if( m_hash != otherId.m_hash ) - return false; - - return m_str == otherId.m_str; - } - - - public bool Equals_fast( Token other ) - { - return m_hash == other.m_hash && m_str == other.m_str; - } - - public override int GetHashCode() - { - return m_hash; - } - - public override string ToString() - { - return m_str; - } - - int m_hash; - String m_str; -} - } diff --git a/Utilities.Interop.cs b/Utilities.Interop.cs index 01d9cb1..dab09bc 100644 --- a/Utilities.Interop.cs +++ b/Utilities.Interop.cs @@ -27,139 +27,139 @@ using System.Runtime.CompilerServices; namespace lib { - /// - /// Utility class. - /// - internal sealed class Interop - { - public static T Pin(ref T source) where T : struct - { - throw new NotImplementedException(); - } + /// + /// Utility class. + /// + internal sealed class Interop + { + public static T Pin( ref T source ) where T : struct + { + throw new NotImplementedException(); + } - public static T IncrementPinned(T source) where T : struct - { - throw new NotImplementedException(); - } + public static T IncrementPinned( T source ) where T : struct + { + throw new NotImplementedException(); + } - public static T AddPinned(T source, int offset) where T : struct - { - throw new NotImplementedException(); - } + public static T AddPinned( T source, int offset ) where T : struct + { + throw new NotImplementedException(); + } - public static void Pin(T data) where T : class - { - throw new NotImplementedException(); - } + public static void Pin( T data ) where T : class + { + throw new NotImplementedException(); + } - public static unsafe void* Fixed(ref T data) - { - throw new NotImplementedException(); - } + public static unsafe void* Fixed( ref T data ) + { + throw new NotImplementedException(); + } - public static unsafe void* FixedOut(out T data) - { - throw new NotImplementedException(); - } + public static unsafe void* FixedOut( out T data ) + { + throw new NotImplementedException(); + } - public static unsafe void* Fixed(T[] data) - { - throw new NotImplementedException(); - } + public static unsafe void* Fixed( T[] data ) + { + throw new NotImplementedException(); + } - public static unsafe void* Cast(ref T data) where T : struct - { - throw new NotImplementedException(); - } + public static unsafe void* Cast( ref T data ) where T : struct + { + throw new NotImplementedException(); + } - public static unsafe void* CastOut(out T data) where T : struct - { - throw new NotImplementedException(); - } + public static unsafe void* CastOut( out T data ) where T : struct + { + throw new NotImplementedException(); + } - public static TCAST[] CastArray(T[] arrayData) - where T : struct - where TCAST : struct - { - throw new NotImplementedException(); - } + public static TCAST[] CastArray( T[] arrayData ) + where T : struct + where TCAST : struct + { + throw new NotImplementedException(); + } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void memcpy(void* pDest, void* pSrc, int count) - { - throw new NotImplementedException(); - } + [MethodImpl( MethodImplOptions.AggressiveInlining )] + public static unsafe void memcpy( void* pDest, void* pSrc, int count ) + { + throw new NotImplementedException(); + } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void memset(void* pDest, byte value, int count) - { - throw new NotImplementedException(); - } + [MethodImpl( MethodImplOptions.AggressiveInlining )] + public static unsafe void memset( void* pDest, byte value, int count ) + { + throw new NotImplementedException(); + } - public static unsafe void* Read(void* pSrc, ref T data) where T : struct - { - throw new NotImplementedException(); - } + public static unsafe void* Read( void* pSrc, ref T data ) where T : struct + { + throw new NotImplementedException(); + } - public static unsafe T ReadInline(void* pSrc) where T : struct - { - throw new NotImplementedException(); - } + public static unsafe T ReadInline( void* pSrc ) where T : struct + { + throw new NotImplementedException(); + } - public static unsafe void WriteInline(void* pDest, ref T data) where T : struct - { - throw new NotImplementedException(); - } + public static unsafe void WriteInline( void* pDest, ref T data ) where T : struct + { + throw new NotImplementedException(); + } - public static unsafe void CopyInline(ref T data, void* pSrc) where T : struct - { - throw new NotImplementedException(); - } + public static unsafe void CopyInline( ref T data, void* pSrc ) where T : struct + { + throw new NotImplementedException(); + } - public static unsafe void CopyInline(void* pDest, ref T srcData) - { - throw new NotImplementedException(); - } + public static unsafe void CopyInline( void* pDest, ref T srcData ) + { + throw new NotImplementedException(); + } - public static unsafe void CopyInlineOut(out T data, void* pSrc) - { - throw new NotImplementedException(); - } + public static unsafe void CopyInlineOut( out T data, void* pSrc ) + { + throw new NotImplementedException(); + } - public static unsafe void* ReadOut(void* pSrc, out T data) where T : struct - { - throw new NotImplementedException(); - } + public static unsafe void* ReadOut( void* pSrc, out T data ) where T : struct + { + throw new NotImplementedException(); + } - public static unsafe void* Read(void* pSrc, T[] data, int offset, int count) where T : struct - { - throw new NotImplementedException(); - } + public static unsafe void* Read( void* pSrc, T[] data, int offset, int count ) where T : struct + { + throw new NotImplementedException(); + } - public static unsafe void* Read2D(void* pSrc, T[,] data, int offset, int count) where T : struct - { - throw new NotImplementedException(); - } + public static unsafe void* Read2D( void* pSrc, T[,] data, int offset, int count ) where T : struct + { + throw new NotImplementedException(); + } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int SizeOf() - { - throw new NotImplementedException(); - } + [MethodImpl( MethodImplOptions.AggressiveInlining )] + public static int SizeOf() + { + throw new NotImplementedException(); + } - public static unsafe void* Write(void* pDest, ref T data) where T : struct - { - throw new NotImplementedException(); - } + public static unsafe void* Write( void* pDest, ref T data ) where T : struct + { + throw new NotImplementedException(); + } - public static unsafe void* Write(void* pDest, T[] data, int offset, int count) where T : struct - { - throw new NotImplementedException(); - } + public static unsafe void* Write( void* pDest, T[] data, int offset, int count ) where T : struct + { + throw new NotImplementedException(); + } - public static unsafe void* Write2D(void* pDest, T[,] data, int offset, int count) where T : struct - { - throw new NotImplementedException(); - } - } + public static unsafe void* Write2D( void* pDest, T[,] data, int offset, int count ) where T : struct + { + throw new NotImplementedException(); + } + } } diff --git a/Utilities.cs b/Utilities.cs index 4f19eaa..18a70ff 100644 --- a/Utilities.cs +++ b/Utilities.cs @@ -36,11 +36,11 @@ using System.Threading; namespace lib { - /// - /// Utility class. - /// - public static class Util - { + /// + /// Utility class. + /// + public static class Util + { /* #if XENKO_PLATFORM_UWP @@ -102,669 +102,196 @@ namespace lib /// The pointer to compare against. /// The size in bytes to compare. /// True if the buffers are equivalent, false otherwise. - public static unsafe bool CompareMemory(IntPtr from, IntPtr against, int sizeToCompare) - { - var pSrc = (byte*)from; - var pDst = (byte*)against; + public static unsafe bool CompareMemory( IntPtr from, IntPtr against, int sizeToCompare ) + { + var pSrc = (byte*)from; + var pDst = (byte*)against; - // Compare 8 bytes. - var numberOf = sizeToCompare >> 3; - while (numberOf > 0) - { - if (*(long*)pSrc != *(long*)pDst) - return false; - pSrc += 8; - pDst += 8; - numberOf--; - } + // Compare 8 bytes. + var numberOf = sizeToCompare >> 3; + while( numberOf > 0 ) + { + if( *(long*)pSrc != *(long*)pDst ) + return false; + pSrc += 8; + pDst += 8; + numberOf--; + } - // Compare remaining bytes. - numberOf = sizeToCompare & 7; - while (numberOf > 0) - { - if (*pSrc != *pDst) - return false; - pSrc++; - pDst++; - numberOf--; - } + // Compare remaining bytes. + numberOf = sizeToCompare & 7; + while( numberOf > 0 ) + { + if( *pSrc != *pDst ) + return false; + pSrc++; + pDst++; + numberOf--; + } - return true; - } + return true; + } - /// - /// Clears the memory. - /// - /// The dest. - /// The value. - /// The size in bytes to clear. - public static void ClearMemory(IntPtr dest, byte value, int sizeInBytesToClear) - { - unsafe - { - Interop.memset((void*)dest, value, sizeInBytesToClear); - } - } + /// + /// Clears the memory. + /// + /// The dest. + /// The value. + /// The size in bytes to clear. + public static void ClearMemory( IntPtr dest, byte value, int sizeInBytesToClear ) + { + unsafe + { + Interop.memset( (void*)dest, value, sizeInBytesToClear ); + } + } - /// - /// Return the sizeof a struct from a CLR. Equivalent to sizeof operator but works on generics too. - /// - /// a struct to evaluate - /// sizeof this struct - public static int SizeOf() where T : struct - { - return Interop.SizeOf(); - } + /// + /// Return the sizeof a struct from a CLR. Equivalent to sizeof operator but works on generics too. + /// + /// a struct to evaluate + /// sizeof this struct + public static int SizeOf() where T : struct + { + return Interop.SizeOf(); + } - /// - /// Return the sizeof an array of struct. Equivalent to sizeof operator but works on generics too. - /// - /// a struct - /// The array of struct to evaluate. - /// sizeof in bytes of this array of struct - public static int SizeOf(T[] array) where T : struct - { - return array == null ? 0 : array.Length * Interop.SizeOf(); - } + /// + /// Return the sizeof an array of struct. Equivalent to sizeof operator but works on generics too. + /// + /// a struct + /// The array of struct to evaluate. + /// sizeof in bytes of this array of struct + public static int SizeOf( T[] array ) where T : struct + { + return array == null ? 0 : array.Length * Interop.SizeOf(); + } - /// - /// Pins the specified source and call an action with the pinned pointer. - /// - /// The type of the structure to pin - /// The source. - /// The pin action to perform on the pinned pointer. - public static void Pin(ref T source, Action pinAction) where T : struct - { - unsafe - { - pinAction((IntPtr)Interop.Fixed(ref source)); - } - } + /// + /// Pins the specified source and call an action with the pinned pointer. + /// + /// The type of the structure to pin + /// The source. + /// The pin action to perform on the pinned pointer. + public static void Pin( ref T source, Action pinAction ) where T : struct + { + unsafe + { + pinAction( (IntPtr)Interop.Fixed( ref source ) ); + } + } - /// - /// Pins the specified source and call an action with the pinned pointer. - /// - /// The type of the structure to pin - /// The source array. - /// The pin action to perform on the pinned pointer. - public static void Pin(T[] source, [NotNull] Action pinAction) where T : struct - { - unsafe - { - pinAction(source == null ? IntPtr.Zero : (IntPtr)Interop.Fixed(source)); - } - } + /// + /// Pins the specified source and call an action with the pinned pointer. + /// + /// The type of the structure to pin + /// The source array. + /// The pin action to perform on the pinned pointer. + public static void Pin( T[] source, [NotNull] Action pinAction ) where T : struct + { + unsafe + { + pinAction( source == null ? IntPtr.Zero : (IntPtr)Interop.Fixed( source ) ); + } + } - /// - /// Covnerts a structured array to an equivalent byte array. - /// - /// The source. - /// The byte array. - public static byte[] ToByteArray(T[] source) where T : struct - { - if (source == null) return null; + /// + /// Covnerts a structured array to an equivalent byte array. + /// + /// The source. + /// The byte array. + public static byte[] ToByteArray( T[] source ) where T : struct + { + if( source == null ) + return null; - var buffer = new byte[SizeOf() * source.Length]; + var buffer = new byte[SizeOf() * source.Length]; - if (source.Length == 0) - return buffer; + if( source.Length == 0 ) + return buffer; - unsafe - { - fixed (void* pBuffer = buffer) - Interop.Write(pBuffer, source, 0, source.Length); - } - return buffer; - } + unsafe + { + fixed ( void* pBuffer = buffer ) + Interop.Write( pBuffer, source, 0, source.Length ); + } + return buffer; + } - /// - /// Reads the specified T data from a memory location. - /// - /// Type of a data to read - /// Memory location to read from. - /// The data read from the memory location - public static T Read(IntPtr source) where T : struct - { - unsafe - { - return Interop.ReadInline((void*)source); - } - } + /// + /// Reads the specified T data from a memory location. + /// + /// Type of a data to read + /// Memory location to read from. + /// The data read from the memory location + public static T Read( IntPtr source ) where T : struct + { + unsafe + { + return Interop.ReadInline( (void*)source ); + } + } - /// - /// Reads the specified T data from a memory location. - /// - /// Type of a data to read - /// Memory location to read from. - /// The data write to. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Read(IntPtr source, ref T data) where T : struct - { - unsafe - { - Interop.CopyInline(ref data, (void*)source); - } - } + /// + /// Reads the specified T data from a memory location. + /// + /// Type of a data to read + /// Memory location to read from. + /// The data write to. + [MethodImpl( MethodImplOptions.AggressiveInlining )] + public static void Read( IntPtr source, ref T data ) where T : struct + { + unsafe + { + Interop.CopyInline( ref data, (void*)source ); + } + } - /// - /// Reads the specified T data from a memory location. - /// - /// Type of a data to read - /// Memory location to read from. - /// The data write to. - public static void ReadOut(IntPtr source, out T data) where T : struct - { - unsafe - { - Interop.CopyInlineOut(out data, (void*)source); - } - } + /// + /// Reads the specified T data from a memory location. + /// + /// Type of a data to read + /// Memory location to read from. + /// The data write to. + public static void ReadOut( IntPtr source, out T data ) where T : struct + { + unsafe + { + Interop.CopyInlineOut( out data, (void*)source ); + } + } - /// - /// Reads the specified T data from a memory location. - /// - /// Type of a data to read - /// Memory location to read from. - /// The data write to. - /// source pointer + sizeof(T) - public static IntPtr ReadAndPosition(IntPtr source, ref T data) where T : struct - { - unsafe - { - return (IntPtr)Interop.Read((void*)source, ref data); - } - } + /// + /// Reads the specified T data from a memory location. + /// + /// Type of a data to read + /// Memory location to read from. + /// The data write to. + /// source pointer + sizeof(T) + public static IntPtr ReadAndPosition( IntPtr source, ref T data ) where T : struct + { + unsafe + { + return (IntPtr)Interop.Read( (void*)source, ref data ); + } + } - /// - /// Reads the specified array T[] data from a memory location. - /// - /// Type of a data to read - /// Memory location to read from. - /// The data write to. - /// The offset in the array to write to. - /// The number of T element to read from the memory location - /// source pointer + sizeof(T) * count - public static IntPtr Read(IntPtr source, T[] data, int offset, int count) where T : struct - { - unsafe - { - return (IntPtr)Interop.Read((void*)source, data, offset, count); - } - } - - /// - /// Writes the specified T data to a memory location. - /// - /// Type of a data to write - /// Memory location to write to. - /// The data to write. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Write(IntPtr destination, ref T data) where T : struct - { - unsafe - { - Interop.CopyInline((void*)destination, ref data); - } - } - - /// - /// Writes the specified T data to a memory location. - /// - /// Type of a data to write - /// Memory location to write to. - /// The data to write. - /// destination pointer + sizeof(T) - public static IntPtr WriteAndPosition(IntPtr destination, ref T data) where T : struct - { - unsafe - { - return (IntPtr)Interop.Write((void*)destination, ref data); - } - } - - /// - /// Writes the specified array T[] data to a memory location. - /// - /// Type of a data to write - /// Memory location to write to. - /// The array of T data to write. - /// The offset in the array to read from. - /// The number of T element to write to the memory location - public static void Write(byte[] destination, T[] data, int offset, int count) where T : struct - { - unsafe - { - fixed (void* pDest = destination) - { - Write((IntPtr)pDest, data, offset, count); - } - } - } - - /// - /// Writes the specified array T[] data to a memory location. - /// - /// Type of a data to write - /// Memory location to write to. - /// The array of T data to write. - /// The offset in the array to read from. - /// The number of T element to write to the memory location - /// destination pointer + sizeof(T) * count - public static IntPtr Write(IntPtr destination, T[] data, int offset, int count) where T : struct - { - unsafe - { - return (IntPtr)Interop.Write((void*)destination, data, offset, count); - } - } - - /// - /// Allocate an aligned memory buffer. - /// - /// Size of the buffer to allocate. - /// Alignment, a positive value which is a power of 2. 16 bytes by default. - /// A pointer to a buffer aligned. - /// - /// To free this buffer, call - /// - public static unsafe IntPtr AllocateMemory(int sizeInBytes, int align = 16) - { - var mask = align - 1; - if ((align & mask) != 0) - { - throw new ArgumentException("Alignment is not power of 2", nameof(align)); - } - var memPtr = Marshal.AllocHGlobal(sizeInBytes + mask + sizeof(void*)); - var ptr = (byte*)((ulong)(memPtr.ToInt32() + sizeof(void*) + mask) & ~(ulong)mask); - ((IntPtr*)ptr)[-1] = memPtr; - return new IntPtr(ptr); - } - - /// - /// Allocate an aligned memory buffer and clear it with a specified value (0 by defaault). - /// - /// Size of the buffer to allocate. - /// Default value used to clear the buffer. - /// Alignment, 16 bytes by default. - /// A pointer to a buffer aligned. - /// - /// To free this buffer, call - /// - public static IntPtr AllocateClearedMemory(int sizeInBytes, byte clearValue = 0, int align = 16) - { - var ptr = AllocateMemory(sizeInBytes, align); - ClearMemory(ptr, clearValue, sizeInBytes); - return ptr; - } - - /// - /// Determines whether the specified memory pointer is aligned in memory. - /// - /// The memory pointer. - /// The align. - /// true if the specified memory pointer is aligned in memory; otherwise, false. - public static bool IsMemoryAligned(IntPtr memoryPtr, int align = 16) - { - return (memoryPtr.ToInt64() & (align - 1)) == 0; - } - - /// - /// Allocate an aligned memory buffer. - /// - /// - /// The buffer must have been allocated with - /// - public static unsafe void FreeMemory(IntPtr alignedBuffer) - { - Marshal.FreeHGlobal(((IntPtr*)alignedBuffer)[-1]); - } - - /// - /// If non-null, disposes the specified object and set it to null, otherwise do nothing. - /// - /// The disposable. - public static void Dispose(ref T disposable) where T : class, IDisposable - { - if (disposable != null) - { - disposable.Dispose(); - disposable = null; - } - } - - /// - /// String helper join method to display an array of object as a single string. - /// - /// The separator. - /// The array. - /// a string with array elements serparated by the seperator - [NotNull] - public static string Join(string separator, T[] array) - { - var text = new StringBuilder(); - if (array != null) - { - for (var i = 0; i < array.Length; i++) - { - if (i > 0) text.Append(separator); - text.Append(array[i]); - } - } - return text.ToString(); - } - - /// - /// String helper join method to display an enumrable of object as a single string. - /// - /// The separator. - /// The enumerable. - /// a string with array elements serparated by the seperator - [NotNull] - public static string Join(string separator, [NotNull] IEnumerable elements) - { - var elementList = new List(); - foreach (var element in elements) - elementList.Add(element.ToString()); - - var text = new StringBuilder(); - for (var i = 0; i < elementList.Count; i++) - { - var element = elementList[i]; - if (i > 0) text.Append(separator); - text.Append(element); - } - return text.ToString(); - } - - /// - /// String helper join method to display an enumrable of object as a single string. - /// - /// The separator. - /// The enumerable. - /// a string with array elements serparated by the seperator - [NotNull] - public static string Join(string separator, [NotNull] IEnumerator elements) - { - var elementList = new List(); - while (elements.MoveNext()) - elementList.Add(elements.Current.ToString()); - - var text = new StringBuilder(); - for (var i = 0; i < elementList.Count; i++) - { - var element = elementList[i]; - if (i > 0) text.Append(separator); - text.Append(element); - } - return text.ToString(); - } - - /// - /// Read stream to a byte[] buffer - /// - /// input stream - /// a byte[] buffer - [NotNull] - public static byte[] ReadStream([NotNull] Stream stream) - { - var readLength = 0; - return ReadStream(stream, ref readLength); - } - - /// - /// Read stream to a byte[] buffer - /// - /// input stream - /// length to read - /// a byte[] buffer - [NotNull] - public static byte[] ReadStream([NotNull] Stream stream, ref int readLength) - { - System.Diagnostics.Debug.Assert(stream != null); - System.Diagnostics.Debug.Assert(stream.CanRead); - var num = readLength; - System.Diagnostics.Debug.Assert(num <= (stream.Length - stream.Position)); - if (num == 0) - readLength = (int)(stream.Length - stream.Position); - num = readLength; - - System.Diagnostics.Debug.Assert(num >= 0); - if (num == 0) - return new byte[0]; - - var buffer = new byte[num]; - var bytesRead = 0; - if (num > 0) - { - do - { - bytesRead += stream.Read(buffer, bytesRead, readLength - bytesRead); - } while (bytesRead < readLength); - } - return buffer; - } - - /// - /// Computes a hashcode for a dictionary. - /// - /// Hashcode for the list. - public static int GetHashCode(IDictionary dict) - { - if (dict == null) - return 0; - - var hashCode = 0; - foreach (DictionaryEntry keyValue in dict) - { - hashCode = (hashCode * 397) ^ keyValue.Key.GetHashCode(); - hashCode = (hashCode * 397) ^ (keyValue.Value?.GetHashCode() ?? 0); - } - return hashCode; - } - - /// - /// Computes a hashcode for an enumeration - /// - /// An enumerator. - /// Hashcode for the list. - public static int GetHashCode(IEnumerable it) - { - if (it == null) - return 0; - - var hashCode = 0; - foreach (var current in it) - { - hashCode = (hashCode * 397) ^ (current?.GetHashCode() ?? 0); - } - return hashCode; - } - - /// - /// Computes a hashcode for an enumeration - /// - /// An enumerator. - /// Hashcode for the list. - public static int GetHashCode(IEnumerator it) - { - if (it == null) - return 0; - - var hashCode = 0; - while (it.MoveNext()) - { - var current = it.Current; - hashCode = (hashCode * 397) ^ (current?.GetHashCode() ?? 0); - } - return hashCode; - } - - /// - /// Compares two collection, element by elements. - /// - /// A "from" enumerator. - /// A "to" enumerator. - /// True if lists are identical. False otherwise. - public static bool Compare(IEnumerable left, IEnumerable right) - { - if (ReferenceEquals(left, right)) - return true; - if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) - return false; - - return Compare(left.GetEnumerator(), right.GetEnumerator()); - } - - /// - /// Compares two collection, element by elements. - /// - /// A "from" enumerator. - /// A "to" enumerator. - /// True if lists are identical. False otherwise. - public static bool Compare(IEnumerator leftIt, IEnumerator rightIt) - { - if (ReferenceEquals(leftIt, rightIt)) - return true; - if (ReferenceEquals(leftIt, null) || ReferenceEquals(rightIt, null)) - return false; - - bool hasLeftNext; - bool hasRightNext; - while (true) - { - hasLeftNext = leftIt.MoveNext(); - hasRightNext = rightIt.MoveNext(); - if (!hasLeftNext || !hasRightNext) - break; - - if (!Equals(leftIt.Current, rightIt.Current)) - return false; - } - - // If there is any left element - if (hasLeftNext != hasRightNext) - return false; - - return true; - } - - /// - /// Compares two collection, element by elements. - /// - /// The collection to compare from. - /// The colllection to compare to. - /// True if lists are identical (but no necessarely of the same time). False otherwise. - public static bool Compare(IDictionary first, IDictionary second) - { - if (ReferenceEquals(first, second)) return true; - if (ReferenceEquals(first, null) || ReferenceEquals(second, null)) return false; - if (first.Count != second.Count) return false; - - var comparer = EqualityComparer.Default; - - foreach (var keyValue in first) - { - TValue secondValue; - if (!second.TryGetValue(keyValue.Key, out secondValue)) return false; - if (!comparer.Equals(keyValue.Value, secondValue)) return false; - } - - // Check that all keys in second are in first - return second.Keys.All(first.ContainsKey); - } - - public static bool Compare(T[] left, T[] right) - { - if (ReferenceEquals(left, right)) - return true; - if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) - return false; - - if (left.Length != right.Length) - return false; - - var comparer = EqualityComparer.Default; - for (var i = 0; i < left.Length; ++i) - { - if (!comparer.Equals(left[i], right[i])) - return false; - } - - return true; - } - - /// - /// Compares two collection, element by elements. - /// - /// The collection to compare from. - /// The colllection to compare to. - /// True if lists are identical (but no necessarely of the same time). False otherwise. - public static bool Compare(ICollection left, ICollection right) - { - if (ReferenceEquals(left, right)) - return true; - if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) - return false; - - if (left.Count != right.Count) - return false; - - var count = 0; - var leftIt = left.GetEnumerator(); - var rightIt = right.GetEnumerator(); - var comparer = EqualityComparer.Default; - while (leftIt.MoveNext() && rightIt.MoveNext()) - { - if (!comparer.Equals(leftIt.Current, rightIt.Current)) - return false; - count++; - } - - // Just double check to make sure that the iterator actually returns - // the exact number of elements - if (count != left.Count) - return false; - - return true; - } - - /// - /// Swaps the value between two references. - /// - /// Type of a data to swap. - /// The left value. - /// The right value. - public static void Swap(ref T left, ref T right) - { - var temp = left; - left = right; - right = temp; - } - - /// - /// Suspends current thread for a . - /// - /// The duration of sleep. - public static void Sleep(TimeSpan sleepTime) - { - var ms = (long)sleepTime.TotalMilliseconds; - if (ms < 0 || ms > int.MaxValue) - { - throw new ArgumentOutOfRangeException(nameof(sleepTime), "Sleep time must be a duration less than '2^31 - 1' milliseconds."); - } - // MH PORTED NativeInvoke.Sleep((int)ms); - Thread.Sleep( (int)ms ); - } - - /// - /// Suspends current thread for a . - /// - /// The duration of sleep in milliseconds. - public static void Sleep(int sleepTimeInMillis) - { - // MH PORTED NativeInvoke.Sleep(sleepTimeInMillis); - Thread.Sleep( sleepTimeInMillis ); - } + /// + /// Reads the specified array T[] data from a memory location. + /// + /// Type of a data to read + /// Memory location to read from. + /// The data write to. + /// The offset in the array to write to. + /// The number of T element to read from the memory location + /// source pointer + sizeof(T) * count + public static IntPtr Read( IntPtr source, T[] data, int offset, int count ) where T : struct + { + unsafe + { + return (IntPtr)Interop.Read( (void*)source, data, offset, count ); + } + } /// /// Writes the specified T data to a memory location. @@ -772,65 +299,547 @@ namespace lib /// Type of a data to write /// Memory location to write to. /// The data to write. - internal static void UnsafeWrite(IntPtr destination, ref T data) - { - unsafe - { - Interop.CopyInline((void*)destination, ref data); - } - } + [MethodImpl( MethodImplOptions.AggressiveInlining )] + public static void Write( IntPtr destination, ref T data ) where T : struct + { + unsafe + { + Interop.CopyInline( (void*)destination, ref data ); + } + } - /// - /// Reads the specified T data from a memory location. - /// - /// Type of a data to read - /// Memory location to read from. - /// The data write to. - internal static void UnsafeReadOut(IntPtr source, out T data) - { - unsafe - { - Interop.CopyInlineOut(out data, (void*)source); - } - } + /// + /// Writes the specified T data to a memory location. + /// + /// Type of a data to write + /// Memory location to write to. + /// The data to write. + /// destination pointer + sizeof(T) + public static IntPtr WriteAndPosition( IntPtr destination, ref T data ) where T : struct + { + unsafe + { + return (IntPtr)Interop.Write( (void*)destination, ref data ); + } + } - /// - /// Return the sizeof a struct from a CLR. Equivalent to sizeof operator but works on generics too. - /// - /// a struct to evaluate - /// sizeof this struct - internal static int UnsafeSizeOf() - { - return Interop.SizeOf(); - } + /// + /// Writes the specified array T[] data to a memory location. + /// + /// Type of a data to write + /// Memory location to write to. + /// The array of T data to write. + /// The offset in the array to read from. + /// The number of T element to write to the memory location + public static void Write( byte[] destination, T[] data, int offset, int count ) where T : struct + { + unsafe + { + fixed ( void* pDest = destination ) + { + Write( (IntPtr)pDest, data, offset, count ); + } + } + } - /// - /// Linq assisted full tree iteration and collection in a single line. - /// Warning, could be slow. - /// - /// The type to iterate. - /// The root item - /// The function to retrieve a child - public static IEnumerable IterateTree(T root, Func> childrenF) - { - var q = new List { root }; - while (q.Any()) - { - var c = q[0]; - q.RemoveAt(0); - q.AddRange(childrenF(c) ?? Enumerable.Empty()); - yield return c; - } - } + /// + /// Writes the specified array T[] data to a memory location. + /// + /// Type of a data to write + /// Memory location to write to. + /// The array of T data to write. + /// The offset in the array to read from. + /// The number of T element to write to the memory location + /// destination pointer + sizeof(T) * count + public static IntPtr Write( IntPtr destination, T[] data, int offset, int count ) where T : struct + { + unsafe + { + return (IntPtr)Interop.Write( (void*)destination, data, offset, count ); + } + } - /// - /// Converts a raw time to a . - /// - /// The delta. - /// The . - public static TimeSpan ConvertRawToTimestamp(long delta) - { - return new TimeSpan(delta == 0 ? 0 : (delta * TimeSpan.TicksPerSecond) / Stopwatch.Frequency); - } - } + /// + /// Allocate an aligned memory buffer. + /// + /// Size of the buffer to allocate. + /// Alignment, a positive value which is a power of 2. 16 bytes by default. + /// A pointer to a buffer aligned. + /// + /// To free this buffer, call + /// + public static unsafe IntPtr AllocateMemory( int sizeInBytes, int align = 16 ) + { + var mask = align - 1; + if( ( align & mask ) != 0 ) + { + throw new ArgumentException( "Alignment is not power of 2", nameof( align ) ); + } + var memPtr = Marshal.AllocHGlobal(sizeInBytes + mask + sizeof(void*)); + var ptr = (byte*)((ulong)(memPtr.ToInt32() + sizeof(void*) + mask) & ~(ulong)mask); + ( (IntPtr*)ptr )[-1] = memPtr; + return new IntPtr( ptr ); + } + + /// + /// Allocate an aligned memory buffer and clear it with a specified value (0 by defaault). + /// + /// Size of the buffer to allocate. + /// Default value used to clear the buffer. + /// Alignment, 16 bytes by default. + /// A pointer to a buffer aligned. + /// + /// To free this buffer, call + /// + public static IntPtr AllocateClearedMemory( int sizeInBytes, byte clearValue = 0, int align = 16 ) + { + var ptr = AllocateMemory(sizeInBytes, align); + ClearMemory( ptr, clearValue, sizeInBytes ); + return ptr; + } + + /// + /// Determines whether the specified memory pointer is aligned in memory. + /// + /// The memory pointer. + /// The align. + /// true if the specified memory pointer is aligned in memory; otherwise, false. + public static bool IsMemoryAligned( IntPtr memoryPtr, int align = 16 ) + { + return ( memoryPtr.ToInt64() & ( align - 1 ) ) == 0; + } + + /// + /// Allocate an aligned memory buffer. + /// + /// + /// The buffer must have been allocated with + /// + public static unsafe void FreeMemory( IntPtr alignedBuffer ) + { + Marshal.FreeHGlobal( ( (IntPtr*)alignedBuffer )[-1] ); + } + + /// + /// If non-null, disposes the specified object and set it to null, otherwise do nothing. + /// + /// The disposable. + public static void Dispose( ref T disposable ) where T : class, IDisposable + { + if( disposable != null ) + { + disposable.Dispose(); + disposable = null; + } + } + + /// + /// String helper join method to display an array of object as a single string. + /// + /// The separator. + /// The array. + /// a string with array elements serparated by the seperator + [NotNull] + public static string Join( string separator, T[] array ) + { + var text = new StringBuilder(); + if( array != null ) + { + for( var i = 0; i < array.Length; i++ ) + { + if( i > 0 ) + text.Append( separator ); + text.Append( array[i] ); + } + } + return text.ToString(); + } + + /// + /// String helper join method to display an enumrable of object as a single string. + /// + /// The separator. + /// The enumerable. + /// a string with array elements serparated by the seperator + [NotNull] + public static string Join( string separator, [NotNull] IEnumerable elements ) + { + var elementList = new List(); + foreach( var element in elements ) + elementList.Add( element.ToString() ); + + var text = new StringBuilder(); + for( var i = 0; i < elementList.Count; i++ ) + { + var element = elementList[i]; + if( i > 0 ) + text.Append( separator ); + text.Append( element ); + } + return text.ToString(); + } + + /// + /// String helper join method to display an enumrable of object as a single string. + /// + /// The separator. + /// The enumerable. + /// a string with array elements serparated by the seperator + [NotNull] + public static string Join( string separator, [NotNull] IEnumerator elements ) + { + var elementList = new List(); + while( elements.MoveNext() ) + elementList.Add( elements.Current.ToString() ); + + var text = new StringBuilder(); + for( var i = 0; i < elementList.Count; i++ ) + { + var element = elementList[i]; + if( i > 0 ) + text.Append( separator ); + text.Append( element ); + } + return text.ToString(); + } + + /// + /// Read stream to a byte[] buffer + /// + /// input stream + /// a byte[] buffer + [NotNull] + public static byte[] ReadStream( [NotNull] Stream stream ) + { + var readLength = 0; + return ReadStream( stream, ref readLength ); + } + + /// + /// Read stream to a byte[] buffer + /// + /// input stream + /// length to read + /// a byte[] buffer + [NotNull] + public static byte[] ReadStream( [NotNull] Stream stream, ref int readLength ) + { + System.Diagnostics.Debug.Assert( stream != null ); + System.Diagnostics.Debug.Assert( stream.CanRead ); + var num = readLength; + System.Diagnostics.Debug.Assert( num <= ( stream.Length - stream.Position ) ); + if( num == 0 ) + readLength = (int)( stream.Length - stream.Position ); + num = readLength; + + System.Diagnostics.Debug.Assert( num >= 0 ); + if( num == 0 ) + return new byte[0]; + + var buffer = new byte[num]; + var bytesRead = 0; + if( num > 0 ) + { + do + { + bytesRead += stream.Read( buffer, bytesRead, readLength - bytesRead ); + } while( bytesRead < readLength ); + } + return buffer; + } + + /// + /// Computes a hashcode for a dictionary. + /// + /// Hashcode for the list. + public static int GetHashCode( IDictionary dict ) + { + if( dict == null ) + return 0; + + var hashCode = 0; + foreach( DictionaryEntry keyValue in dict ) + { + hashCode = ( hashCode * 397 ) ^ keyValue.Key.GetHashCode(); + hashCode = ( hashCode * 397 ) ^ ( keyValue.Value?.GetHashCode() ?? 0 ); + } + return hashCode; + } + + /// + /// Computes a hashcode for an enumeration + /// + /// An enumerator. + /// Hashcode for the list. + public static int GetHashCode( IEnumerable it ) + { + if( it == null ) + return 0; + + var hashCode = 0; + foreach( var current in it ) + { + hashCode = ( hashCode * 397 ) ^ ( current?.GetHashCode() ?? 0 ); + } + return hashCode; + } + + /// + /// Computes a hashcode for an enumeration + /// + /// An enumerator. + /// Hashcode for the list. + public static int GetHashCode( IEnumerator it ) + { + if( it == null ) + return 0; + + var hashCode = 0; + while( it.MoveNext() ) + { + var current = it.Current; + hashCode = ( hashCode * 397 ) ^ ( current?.GetHashCode() ?? 0 ); + } + return hashCode; + } + + /// + /// Compares two collection, element by elements. + /// + /// A "from" enumerator. + /// A "to" enumerator. + /// True if lists are identical. False otherwise. + public static bool Compare( IEnumerable left, IEnumerable right ) + { + if( ReferenceEquals( left, right ) ) + return true; + if( ReferenceEquals( left, null ) || ReferenceEquals( right, null ) ) + return false; + + return Compare( left.GetEnumerator(), right.GetEnumerator() ); + } + + /// + /// Compares two collection, element by elements. + /// + /// A "from" enumerator. + /// A "to" enumerator. + /// True if lists are identical. False otherwise. + public static bool Compare( IEnumerator leftIt, IEnumerator rightIt ) + { + if( ReferenceEquals( leftIt, rightIt ) ) + return true; + if( ReferenceEquals( leftIt, null ) || ReferenceEquals( rightIt, null ) ) + return false; + + bool hasLeftNext; + bool hasRightNext; + while( true ) + { + hasLeftNext = leftIt.MoveNext(); + hasRightNext = rightIt.MoveNext(); + if( !hasLeftNext || !hasRightNext ) + break; + + if( !Equals( leftIt.Current, rightIt.Current ) ) + return false; + } + + // If there is any left element + if( hasLeftNext != hasRightNext ) + return false; + + return true; + } + + /// + /// Compares two collection, element by elements. + /// + /// The collection to compare from. + /// The colllection to compare to. + /// True if lists are identical (but no necessarely of the same time). False otherwise. + public static bool Compare( IDictionary first, IDictionary second ) + { + if( ReferenceEquals( first, second ) ) + return true; + if( ReferenceEquals( first, null ) || ReferenceEquals( second, null ) ) + return false; + if( first.Count != second.Count ) + return false; + + var comparer = EqualityComparer.Default; + + foreach( var keyValue in first ) + { + TValue secondValue; + if( !second.TryGetValue( keyValue.Key, out secondValue ) ) + return false; + if( !comparer.Equals( keyValue.Value, secondValue ) ) + return false; + } + + // Check that all keys in second are in first + return second.Keys.All( first.ContainsKey ); + } + + public static bool Compare( T[] left, T[] right ) + { + if( ReferenceEquals( left, right ) ) + return true; + if( ReferenceEquals( left, null ) || ReferenceEquals( right, null ) ) + return false; + + if( left.Length != right.Length ) + return false; + + var comparer = EqualityComparer.Default; + for( var i = 0; i < left.Length; ++i ) + { + if( !comparer.Equals( left[i], right[i] ) ) + return false; + } + + return true; + } + + /// + /// Compares two collection, element by elements. + /// + /// The collection to compare from. + /// The colllection to compare to. + /// True if lists are identical (but no necessarely of the same time). False otherwise. + public static bool Compare( ICollection left, ICollection right ) + { + if( ReferenceEquals( left, right ) ) + return true; + if( ReferenceEquals( left, null ) || ReferenceEquals( right, null ) ) + return false; + + if( left.Count != right.Count ) + return false; + + var count = 0; + var leftIt = left.GetEnumerator(); + var rightIt = right.GetEnumerator(); + var comparer = EqualityComparer.Default; + while( leftIt.MoveNext() && rightIt.MoveNext() ) + { + if( !comparer.Equals( leftIt.Current, rightIt.Current ) ) + return false; + count++; + } + + // Just double check to make sure that the iterator actually returns + // the exact number of elements + if( count != left.Count ) + return false; + + return true; + } + + /// + /// Swaps the value between two references. + /// + /// Type of a data to swap. + /// The left value. + /// The right value. + public static void Swap( ref T left, ref T right ) + { + var temp = left; + left = right; + right = temp; + } + + /// + /// Suspends current thread for a . + /// + /// The duration of sleep. + public static void Sleep( TimeSpan sleepTime ) + { + var ms = (long)sleepTime.TotalMilliseconds; + if( ms < 0 || ms > int.MaxValue ) + { + throw new ArgumentOutOfRangeException( nameof( sleepTime ), "Sleep time must be a duration less than '2^31 - 1' milliseconds." ); + } + // MH PORTED NativeInvoke.Sleep((int)ms); + Thread.Sleep( (int)ms ); + } + + /// + /// Suspends current thread for a . + /// + /// The duration of sleep in milliseconds. + public static void Sleep( int sleepTimeInMillis ) + { + // MH PORTED NativeInvoke.Sleep(sleepTimeInMillis); + Thread.Sleep( sleepTimeInMillis ); + } + + /// + /// Writes the specified T data to a memory location. + /// + /// Type of a data to write + /// Memory location to write to. + /// The data to write. + internal static void UnsafeWrite( IntPtr destination, ref T data ) + { + unsafe + { + Interop.CopyInline( (void*)destination, ref data ); + } + } + + /// + /// Reads the specified T data from a memory location. + /// + /// Type of a data to read + /// Memory location to read from. + /// The data write to. + internal static void UnsafeReadOut( IntPtr source, out T data ) + { + unsafe + { + Interop.CopyInlineOut( out data, (void*)source ); + } + } + + /// + /// Return the sizeof a struct from a CLR. Equivalent to sizeof operator but works on generics too. + /// + /// a struct to evaluate + /// sizeof this struct + internal static int UnsafeSizeOf() + { + return Interop.SizeOf(); + } + + /// + /// Linq assisted full tree iteration and collection in a single line. + /// Warning, could be slow. + /// + /// The type to iterate. + /// The root item + /// The function to retrieve a child + public static IEnumerable IterateTree( T root, Func> childrenF ) + { + var q = new List { root }; + while( q.Any() ) + { + var c = q[0]; + q.RemoveAt( 0 ); + q.AddRange( childrenF( c ) ?? Enumerable.Empty() ); + yield return c; + } + } + + /// + /// Converts a raw time to a . + /// + /// The delta. + /// The . + public static TimeSpan ConvertRawToTimestamp( long delta ) + { + return new TimeSpan( delta == 0 ? 0 : ( delta * TimeSpan.TicksPerSecond ) / Stopwatch.Frequency ); + } + } } diff --git a/VersionFormatter.cs b/VersionFormatter.cs index 72159df..85883fd 100644 --- a/VersionFormatter.cs +++ b/VersionFormatter.cs @@ -28,8 +28,8 @@ namespace lib Boolean, EndStream, } - - + + public VersionFormatter() { // @@ -37,27 +37,27 @@ namespace lib // } - + #region Useless - public ISurrogateSelector SurrogateSelector + public ISurrogateSelector SurrogateSelector { get { return null; - } - + } + set { } } - - public SerializationBinder Binder + + public SerializationBinder Binder { get { return null; - } - + } + set { } @@ -68,8 +68,8 @@ namespace lib get { return new StreamingContext(); - } - + } + set { } @@ -85,21 +85,21 @@ namespace lib { //Default is 4k //BufferedStream bufStream = new BufferedStream( stream ); - + BinaryWriter writer = new BinaryWriter( stream ); - + writeObject( writer, obj ); - + while( m_objectsToBeDeserialized.Count != 0 ) { object objToDes = m_objectsToBeDeserialized.Dequeue(); - + writeObject( writer, objToDes ); } - + writer.Write( (char)ETypes.EndStream ); } - + void writeRefAndSched( BinaryWriter writer, object obj ) { //if( m_alreadyDeserialzied[ obj.GetType().GetArrayRank( @@ -110,15 +110,15 @@ namespace lib return; } - + //Now write the address. //Bad bad. Need to do this correctly. int objRef = obj.GetHashCode(); writer.Write( objRef ); - if( m_alreadyDeserialzied[ obj ] == null ) + if( m_alreadyDeserialzied[obj] == null ) { - m_alreadyDeserialzied[ obj ] = obj; + m_alreadyDeserialzied[obj] = obj; m_objectsToBeDeserialized.Enqueue( obj ); } } @@ -126,19 +126,19 @@ namespace lib void dispatchWrite( BinaryWriter writer, object parentObj, FieldInfo fi ) { string typeName = fi.FieldType.Name; - + string name = fi.Name; - + if( fi.IsNotSerialized ) { return; } - + if( fi.FieldType.IsArray ) { writer.Write( (char)ETypes.Array ); writer.Write( name.GetHashCode() ); - + writeArray( writer, (Array)fi.GetValue( parentObj ) ); } else if( ( fi.FieldType.IsClass || fi.FieldType.IsInterface ) && typeName != "String" ) @@ -160,43 +160,43 @@ namespace lib switch( typeName ) { case "Int32": - writer.Write( (char)ETypes.Int32 ); - writer.Write( name.GetHashCode() ); + writer.Write( (char)ETypes.Int32 ); + writer.Write( name.GetHashCode() ); - write( writer, Convert.ToInt32( fi.GetValue( parentObj ) ) ); + write( writer, Convert.ToInt32( fi.GetValue( parentObj ) ) ); break; case "Single": - writer.Write( (char)ETypes.Single ); - writer.Write( name.GetHashCode() ); + writer.Write( (char)ETypes.Single ); + writer.Write( name.GetHashCode() ); - write( writer, Convert.ToSingle( fi.GetValue( parentObj ) ) ); - break; + write( writer, Convert.ToSingle( fi.GetValue( parentObj ) ) ); + break; case "Double": - writer.Write( (char)ETypes.Double ); - writer.Write( name.GetHashCode() ); + writer.Write( (char)ETypes.Double ); + writer.Write( name.GetHashCode() ); - write( writer, Convert.ToDouble( fi.GetValue( parentObj ) ) ); - break; + write( writer, Convert.ToDouble( fi.GetValue( parentObj ) ) ); + break; case "Char": - writer.Write( (char)ETypes.Char ); - writer.Write( name.GetHashCode() ); + writer.Write( (char)ETypes.Char ); + writer.Write( name.GetHashCode() ); - write( writer, Convert.ToChar( fi.GetValue( parentObj ) ) ); - break; + write( writer, Convert.ToChar( fi.GetValue( parentObj ) ) ); + break; case "String": - writer.Write( (char)ETypes.String ); - writer.Write( name.GetHashCode() ); + writer.Write( (char)ETypes.String ); + writer.Write( name.GetHashCode() ); - write( writer, Convert.ToString( fi.GetValue( parentObj ) ) ); - break; + write( writer, Convert.ToString( fi.GetValue( parentObj ) ) ); + break; case "Boolean": - writer.Write( (char)ETypes.Boolean ); - writer.Write( name.GetHashCode() ); + writer.Write( (char)ETypes.Boolean ); + writer.Write( name.GetHashCode() ); - writer.Write( Convert.ToBoolean( fi.GetValue( parentObj ) ) ); - break; + writer.Write( Convert.ToBoolean( fi.GetValue( parentObj ) ) ); + break; default: - Console.WriteLine( "VersionFormatter does not understand type " + typeName ); + Console.WriteLine( "VersionFormatter does not understand type " + typeName ); break; } } @@ -209,48 +209,48 @@ namespace lib writer.Write( (int)-1 ); return; } - + writer.Write( array.Length ); - + foreach( object obj in array ) { writeRefAndSched( writer, obj ); } } - + void getAllFields( object obj, ArrayList list ) { Type t = obj.GetType(); - + while( t != null ) { FieldInfo[] fiArr = t.GetFields( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly ); list.AddRange( fiArr ); - + t = t.BaseType; } } - - + + void writeObject( BinaryWriter writer, object obj ) { Type objType = obj.GetType(); - + writer.Write( (char)ETypes.Object ); writer.Write( objType.FullName ); - + int objRef = obj.GetHashCode(); writer.Write( objRef ); - + ArrayList list = new ArrayList(); - + getAllFields( obj, list ); - + foreach( FieldInfo fi in list ) { dispatchWrite( writer, obj, fi ); } - + writer.Write( (char)ETypes.EndObject ); } @@ -299,76 +299,76 @@ namespace lib { public Fixup( int guid, object obj, FieldInfo fi ) { - m_guid= guid; + m_guid = guid; m_obj = obj; - m_fi = fi; + m_fi = fi; } - + public Fixup( int guid, object obj, int index ) { m_guid = guid; - m_obj = obj; - m_index= index; + m_obj = obj; + m_index = index; } - + public readonly int m_guid = 0; public readonly object m_obj = null; - + public readonly FieldInfo m_fi = null; public readonly int m_index= -1; - + } Hashtable m_mapGUIDToObject = new Hashtable(); ArrayList m_fixupList = new ArrayList(); - + ArrayList m_desObjects = new ArrayList(); public object Deserialize( Stream stream ) { BinaryReader reader = new BinaryReader( stream ); - + object objRoot = null; //Read in the first object. { ETypes type = (ETypes)reader.ReadChar(); - + Debug.Assert( type == ETypes.Object ); - + objRoot = readObject( reader ); m_desObjects.Add( objRoot ); } - + bool readObjects = true; - + while( readObjects ) { ETypes type = (ETypes)reader.ReadChar(); - + Debug.Assert( type == ETypes.Object || type == ETypes.EndStream ); - + if( type == ETypes.Object ) { object obj = readObject( reader ); - + m_desObjects.Add( obj ); } else { Debug.Assert( type == ETypes.EndStream ); - + readObjects = false; } } - + foreach( Fixup fu in m_fixupList ) { //Fixup fix = m_fixups[ - + object obj = m_mapGUIDToObject[ fu.m_guid ]; - + if( obj != null ) { if( fu.m_fi != null ) @@ -378,10 +378,10 @@ namespace lib else { Debug.Assert( fu.m_index >= 0 ); - + object []array = (object [])fu.m_obj; - - array[ fu.m_index ] = obj; + + array[fu.m_index] = obj; } } else @@ -389,39 +389,39 @@ namespace lib Console.WriteLine( "Obj to ref is null." ); } } - + foreach( object obj in m_desObjects ) { if( typeof( IDeserializationCallback ).IsAssignableFrom( obj.GetType() ) ) { IDeserializationCallback desCB = (IDeserializationCallback)obj; - + if( desCB != null ) { desCB.OnDeserialization( this ); } } } - + return objRoot; } - - + + bool dispatchRead( BinaryReader reader, object obj, Hashtable ht ) { - + //Read the type ETypes type = (ETypes)reader.ReadChar(); - + if( type == ETypes.EndObject ) { return false; } - + int nameHash = reader.ReadInt32(); - - FieldInfo fi = (FieldInfo)ht[ nameHash ]; + + FieldInfo fi = (FieldInfo)ht[ nameHash ]; if( fi == null ) { @@ -429,38 +429,38 @@ namespace lib } try - { + { switch( type ) { case ETypes.Array: - readArray( reader, obj, fi ); + readArray( reader, obj, fi ); break; case ETypes.Int32: - readInt( reader, obj, fi ); + readInt( reader, obj, fi ); break; case ETypes.Single: - readSingle( reader, obj, fi ); - break; + readSingle( reader, obj, fi ); + break; case ETypes.Double: - readDouble( reader, obj, fi ); - break; + readDouble( reader, obj, fi ); + break; case ETypes.Char: - readChar( reader, obj, fi ); - break; + readChar( reader, obj, fi ); + break; case ETypes.Boolean: - readBool( reader, obj, fi ); + readBool( reader, obj, fi ); break; case ETypes.String: - readString( reader, obj, fi ); + readString( reader, obj, fi ); break; case ETypes.Ref: - readRef( reader, obj, fi ); + readRef( reader, obj, fi ); break; case ETypes.Object: - readObject( reader ); - break; + readObject( reader ); + break; default: - Debug.Fail( "Unknown type on read." ); + Debug.Fail( "Unknown type on read." ); break; } } @@ -469,7 +469,7 @@ namespace lib Console.WriteLine( "Exception: " + ex.Message ); Console.WriteLine( "Stack: " + ex.StackTrace ); } - + return true; } @@ -477,116 +477,118 @@ namespace lib object createObject( string objTypeName ) { Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies(); - + foreach( Assembly a in ass ) { Type t = a.GetType( objTypeName ); - + if( t != null ) { object obj = FormatterServices.GetUninitializedObject( t ); - + if( obj != null ) { return obj; } } } - + return null; } - - + + object readObject( BinaryReader reader ) { //ETypes type = (ETypes)reader.ReadChar(); - + //Debug.Assert( type == ETypes.Object, "Expecting type Object" ); - + string objTypeName = reader.ReadString(); int objGUID = reader.ReadInt32(); - + try { object obj = createObject( objTypeName ); - - m_mapGUIDToObject[ objGUID ] = obj; - + + m_mapGUIDToObject[objGUID] = obj; + ArrayList list = new ArrayList(); Hashtable ht = new Hashtable(); - + if( obj != null ) { getAllFields( obj, list ); - + foreach( FieldInfo fi in list ) { - ht[ fi.Name.GetHashCode() ] = fi; + ht[fi.Name.GetHashCode()] = fi; } } - + while( dispatchRead( reader, obj, ht ) ) { } - + return obj; } catch( Exception ex ) { Console.WriteLine( "Exception: " + ex.Message ); } - + return null; } - + void readArray( BinaryReader reader, object obj, FieldInfo fi ) { int length = reader.ReadInt32(); - + if( length < 0 ) { - if( fi == null ) return; - + if( fi == null ) + return; + fi.SetValue( obj, null ); - + return; } - + object[] array = new object[length]; - + if( fi != null ) { fi.SetValue( obj, array ); } - - for( int i=0; i - /// - /// - public class XmlFormatter : IFormatter +/* +/// +/// +/// +public class XmlFormatter : IFormatter +{ + public enum ETypes { - public enum ETypes + Array, + Int32, + Ref, + Object, + EndObject, + Single, + Double, + Char, + String, + Boolean, + EndStream, + } + + + public XmlFormatter() + { + // + // TODO: Add constructor logic here + // + } + + + #region Useless + public ISurrogateSelector SurrogateSelector + { + get { - Array, - Int32, - Ref, - Object, - EndObject, - Single, - Double, - Char, - String, - Boolean, - EndStream, - } - - - public XmlFormatter() - { - // - // TODO: Add constructor logic here - // - } - - - #region Useless - public ISurrogateSelector SurrogateSelector - { - get - { - return null; - } - - set - { - } - } - - public SerializationBinder Binder - { - get - { - return null; - } - - set - { - } - } - - public StreamingContext Context - { - get - { - return new StreamingContext(); - } - - set - { - } - } - #endregion Useless - - Queue m_objectsToBeDeserialized = new Queue(); - Hashtable m_alreadyDeserialzied = new Hashtable(); - //int m_GUID = 0; - - #region Serialize - public void Serialize( System.IO.Stream stream, object obj ) - { - //Default is 4k - //BufferedStream bufStream = new BufferedStream( stream ); - - TextWriter writer = new StreamWriter( stream ); - - writeObject( writer, obj ); - - while( m_objectsToBeDeserialized.Count != 0 ) - { - object objToDes = m_objectsToBeDeserialized.Dequeue(); - - writeObject( writer, objToDes ); - } - - writer.Write( (char)ETypes.EndStream ); - } - - void writeRefAndSched( TextWriter writer, object obj ) - { - //if( m_alreadyDeserialzied[ obj.GetType().GetArrayRank( - - if( obj == null ) - { - writer.Write( 0 ); - return; - } - - - //Now write the address. - //Bad bad. Need to do this correctly. - int objRef = obj.GetHashCode(); - writer.Write( objRef ); - - if( m_alreadyDeserialzied[ obj ] == null ) - { - m_alreadyDeserialzied[ obj ] = obj; - m_objectsToBeDeserialized.Enqueue( obj ); - } - } - - void dispatchWrite( TextWriter writer, object parentObj, FieldInfo fi ) - { - string typeName = fi.FieldType.Name; - - string name = fi.Name; - - if( fi.IsNotSerialized ) - { - return; - } - - if( fi.FieldType.IsArray ) - { - writer.Write( (char)ETypes.Array ); - writer.Write( name.GetHashCode() ); - - writeArray( writer, (Array)fi.GetValue( parentObj ) ); - } - else if( ( fi.FieldType.IsClass || fi.FieldType.IsInterface ) && typeName != "String" ) - { - writer.Write( (char)ETypes.Ref ); - writer.Write( name.GetHashCode() ); - - writeRefAndSched( writer, fi.GetValue( parentObj ) ); - } - else if( fi.FieldType.IsEnum ) - { - writer.Write( (char)ETypes.Int32 ); - writer.Write( name.GetHashCode() ); - - writer.Write( Convert.ToInt32( fi.GetValue( parentObj ) ) ); - } - else - { - switch( typeName ) - { - case "Int32": - writer.Write( (char)ETypes.Int32 ); - writer.Write( name.GetHashCode() ); - - writer.Write( Convert.ToInt32( fi.GetValue( parentObj ) ) ); - break; - case "Single": - writer.Write( (char)ETypes.Single ); - writer.Write( name.GetHashCode() ); - - writer.Write( Convert.ToSingle( fi.GetValue( parentObj ) ) ); - break; - case "Double": - writer.Write( (char)ETypes.Double ); - writer.Write( name.GetHashCode() ); - - writer.Write( Convert.ToDouble( fi.GetValue( parentObj ) ) ); - break; - case "Char": - writer.Write( (char)ETypes.Char ); - writer.Write( name.GetHashCode() ); - - writer.Write( Convert.ToChar( fi.GetValue( parentObj ) ) ); - break; - case "String": - writer.Write( (char)ETypes.String ); - writer.Write( name.GetHashCode() ); - - writer.Write( Convert.ToString( fi.GetValue( parentObj ) ) ); - break; - case "Boolean": - writer.Write( (char)ETypes.Boolean ); - writer.Write( name.GetHashCode() ); - - writer.Write( Convert.ToBoolean( fi.GetValue( parentObj ) ) ); - break; - default: - Console.WriteLine( "VersionFormatter does not understand type " + typeName ); - break; - } - } - } - - void writeArray( TextWriter writer, Array array ) - { - if( array == null ) - { - writer.Write( (int)-1 ); - return; - } - - writer.Write( array.Length ); - - foreach( object obj in array ) - { - writeRefAndSched( writer, obj ); - } - } - - void getAllFields( object obj, ArrayList list ) - { - Type t = obj.GetType(); - - while( t != null ) - { - FieldInfo[] fiArr = t.GetFields( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly ); - list.AddRange( fiArr ); - - t = t.BaseType; - } - } - - - void writeObject( TextWriter writer, object obj ) - { - Type objType = obj.GetType(); - - writer.Write( (char)ETypes.Object ); - writer.Write( objType.FullName ); - - int objRef = obj.GetHashCode(); - writer.Write( objRef ); - - ArrayList list = new ArrayList(); - - getAllFields( obj, list ); - - foreach( FieldInfo fi in list ) - { - dispatchWrite( writer, obj, fi ); - } - - writer.Write( (char)ETypes.EndObject ); - } - - void write( TextWriter wr, TType val ) - { - //wr.Write( val ); - } - - /* - void writeInt( TextWriter writer, int val ) - { - writer.Write( val ); - } - - void writeSingle( TextWriter writer, float val ) - { - writer.Write( val ); - } - - void writeDouble( TextWriter writer, double val ) - { - writer.Write( val ); - } - - void writeChar( TextWriter writer, char val ) - { - writer.Write( val ); - } - - void writeString( TextWriter writer, string val ) - { - writer.Write( val ); - } - - void writeBool( TextWriter writer, bool val ) - { - writer.Write( val ); - } - * / - #endregion Serialize - - - #region Deserialize - - class Fixup - { - public Fixup( int guid, object obj, FieldInfo fi ) - { - m_guid= guid; - m_obj = obj; - m_fi = fi; - } - - XmlFormatter - - public Fixup( int guid, object obj, int index ) - { - m_guid = guid; - m_obj = obj; - m_index= index; - } - - public readonly int m_guid = 0; - public readonly object m_obj = null; - - public readonly FieldInfo m_fi = null; - public readonly int m_index= -1; - - } - - Hashtable m_mapGUIDToObject = new Hashtable(); - ArrayList m_fixupList = new ArrayList(); - - ArrayList m_desObjects = new ArrayList(); - - public object Deserialize( System.IO.Stream stream ) - { - StreamReader reader = new StreamReader( stream ); - - object objRoot = null; - - //Read in the first object. - { - ETypes type = (ETypes)reader.ReadChar(); - - Debug.Assert( type == ETypes.Object ); - - objRoot = readObject( reader ); - - m_desObjects.Add( objRoot ); - } - - bool readObjects = true; - - while( readObjects ) - { - ETypes type = (ETypes)reader.ReadChar(); - - Debug.Assert( type == ETypes.Object || type == ETypes.EndStream ); - - if( type == ETypes.Object ) - { - object obj = readObject( reader ); - - m_desObjects.Add( obj ); - } - else - { - Debug.Assert( type == ETypes.EndStream ); - - readObjects = false; - } - } - - foreach( Fixup fu in m_fixupList ) - { - //Fixup fix = m_fixups[ - - object obj = m_mapGUIDToObject[ fu.m_guid ]; - - if( obj != null ) - { - if( fu.m_fi != null ) - { - fu.m_fi.SetValue( fu.m_obj, obj ); - } - else - { - Debug.Assert( fu.m_index >= 0 ); - - object []array = (object [])fu.m_obj; - - array[ fu.m_index ] = obj; - } - } - else - { - Console.WriteLine( "Obj to ref is null." ); - } - } - - foreach( object obj in m_desObjects ) - { - if( typeof( IDeserializationCallback ).IsAssignableFrom( obj.GetType() ) ) - { - IDeserializationCallback desCB = (IDeserializationCallback)obj; - - if( desCB != null ) - { - desCB.OnDeserialization( this ); - } - } - } - - return objRoot; - } - - - - bool dispatchRead( StreamReader reader, object obj, Hashtable ht ) - { - - //Read the type - ETypes type = (ETypes)reader.ReadChar(); - - if( type == ETypes.EndObject ) - { - return false; - } - - int nameHash = reader.ReadInt32(); - - FieldInfo fi = (FieldInfo)ht[ nameHash ]; - - if( fi == null ) - { - Console.WriteLine( "Field no longer exists" ); - } - - try - { - switch( type ) - { - case ETypes.Array: - readArray( reader, obj, fi ); - break; - case ETypes.Int32: - readInt( reader, obj, fi ); - break; - case ETypes.Single: - readSingle( reader, obj, fi ); - break; - case ETypes.Double: - readDouble( reader, obj, fi ); - break; - case ETypes.Char: - readChar( reader, obj, fi ); - break; - case ETypes.Boolean: - readBool( reader, obj, fi ); - break; - case ETypes.String: - readString( reader, obj, fi ); - break; - case ETypes.Ref: - readRef( reader, obj, fi ); - break; - case ETypes.Object: - readObject( reader ); - break; - default: - Debug.Fail( "Unknown type on read." ); - break; - } - } - catch( Exception ex ) - { - Console.WriteLine( "Exception: " + ex.Message ); - Console.WriteLine( "Stack: " + ex.StackTrace ); - } - - - return true; - } - - object createObject( string objTypeName ) - { - Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies(); - - foreach( Assembly a in ass ) - { - Type t = a.GetType( objTypeName ); - - if( t != null ) - { - object obj = FormatterServices.GetUninitializedObject( t ); - - if( obj != null ) - { - return obj; - } - } - } - return null; - } - - - object readObject( StreamReader reader ) + } + + set + { + } + } + + public SerializationBinder Binder + { + get { - //ETypes type = (ETypes)reader.ReadChar(); - - //Debug.Assert( type == ETypes.Object, "Expecting type Object" ); - - string objTypeName = reader.ReadString(); - int objGUID = reader.ReadInt32(); - - try - { - object obj = createObject( objTypeName ); - - m_mapGUIDToObject[ objGUID ] = obj; - - ArrayList list = new ArrayList(); - Hashtable ht = new Hashtable(); - - if( obj != null ) - { - getAllFields( obj, list ); - - foreach( FieldInfo fi in list ) - { - ht[ fi.Name.GetHashCode() ] = fi; - } - } - - while( dispatchRead( reader, obj, ht ) ) - { - } - - return obj; - } - catch( Exception ex ) - { - Console.WriteLine( "Exception: " + ex.Message ); - } - return null; - } - - void readArray( StreamReader reader, object obj, FieldInfo fi ) + } + + set { - int length = reader.ReadInt32(); - - if( length < 0 ) + } + } + + public StreamingContext Context + { + get + { + return new StreamingContext(); + } + + set + { + } + } + #endregion Useless + + Queue m_objectsToBeDeserialized = new Queue(); + Hashtable m_alreadyDeserialzied = new Hashtable(); + //int m_GUID = 0; + + #region Serialize + public void Serialize( System.IO.Stream stream, object obj ) + { + //Default is 4k + //BufferedStream bufStream = new BufferedStream( stream ); + + TextWriter writer = new StreamWriter( stream ); + + writeObject( writer, obj ); + + while( m_objectsToBeDeserialized.Count != 0 ) + { + object objToDes = m_objectsToBeDeserialized.Dequeue(); + + writeObject( writer, objToDes ); + } + + writer.Write( (char)ETypes.EndStream ); + } + + void writeRefAndSched( TextWriter writer, object obj ) + { + //if( m_alreadyDeserialzied[ obj.GetType().GetArrayRank( + + if( obj == null ) + { + writer.Write( 0 ); + return; + } + + + //Now write the address. + //Bad bad. Need to do this correctly. + int objRef = obj.GetHashCode(); + writer.Write( objRef ); + + if( m_alreadyDeserialzied[ obj ] == null ) + { + m_alreadyDeserialzied[ obj ] = obj; + m_objectsToBeDeserialized.Enqueue( obj ); + } + } + + void dispatchWrite( TextWriter writer, object parentObj, FieldInfo fi ) + { + string typeName = fi.FieldType.Name; + + string name = fi.Name; + + if( fi.IsNotSerialized ) + { + return; + } + + if( fi.FieldType.IsArray ) + { + writer.Write( (char)ETypes.Array ); + writer.Write( name.GetHashCode() ); + + writeArray( writer, (Array)fi.GetValue( parentObj ) ); + } + else if( ( fi.FieldType.IsClass || fi.FieldType.IsInterface ) && typeName != "String" ) + { + writer.Write( (char)ETypes.Ref ); + writer.Write( name.GetHashCode() ); + + writeRefAndSched( writer, fi.GetValue( parentObj ) ); + } + else if( fi.FieldType.IsEnum ) + { + writer.Write( (char)ETypes.Int32 ); + writer.Write( name.GetHashCode() ); + + writer.Write( Convert.ToInt32( fi.GetValue( parentObj ) ) ); + } + else + { + switch( typeName ) { - if( fi == null ) return; - - fi.SetValue( obj, null ); - - return; - } - - object[] array = new object[length]; - - if( fi != null ) - { - fi.SetValue( obj, array ); - } - - for( int i=0; i( TextWriter wr, TType val ) + { + //wr.Write( val ); + } + + /* + void writeInt( TextWriter writer, int val ) + { + writer.Write( val ); + } + + void writeSingle( TextWriter writer, float val ) + { + writer.Write( val ); + } + + void writeDouble( TextWriter writer, double val ) + { + writer.Write( val ); + } + + void writeChar( TextWriter writer, char val ) + { + writer.Write( val ); + } + + void writeString( TextWriter writer, string val ) + { + writer.Write( val ); + } + + void writeBool( TextWriter writer, bool val ) + { + writer.Write( val ); + } + * / + #endregion Serialize + + + #region Deserialize + + class Fixup + { + public Fixup( int guid, object obj, FieldInfo fi ) { - char val = reader.ReadChar(); - - if( fi == null ) return; - - fi.SetValue( obj, val ); + m_guid= guid; + m_obj = obj; + m_fi = fi; } - - void readString( StreamReader reader, object obj, FieldInfo fi ) + + XmlFormatter + + public Fixup( int guid, object obj, int index ) { - string val = reader.ReadString(); - - if( fi == null ) return; - - fi.SetValue( obj, val ); + m_guid = guid; + m_obj = obj; + m_index= index; } - - void readBool( StreamReader reader, object obj, FieldInfo fi ) - { - bool val = reader.ReadBoolean(); - - if( fi == null ) return; - - fi.SetValue( obj, val ); - } - - #endregion Deserialize - + + public readonly int m_guid = 0; + public readonly object m_obj = null; + + public readonly FieldInfo m_fi = null; + public readonly int m_index= -1; } - */ + + Hashtable m_mapGUIDToObject = new Hashtable(); + ArrayList m_fixupList = new ArrayList(); + + ArrayList m_desObjects = new ArrayList(); + + public object Deserialize( System.IO.Stream stream ) + { + StreamReader reader = new StreamReader( stream ); + + object objRoot = null; + + //Read in the first object. + { + ETypes type = (ETypes)reader.ReadChar(); + + Debug.Assert( type == ETypes.Object ); + + objRoot = readObject( reader ); + + m_desObjects.Add( objRoot ); + } + + bool readObjects = true; + + while( readObjects ) + { + ETypes type = (ETypes)reader.ReadChar(); + + Debug.Assert( type == ETypes.Object || type == ETypes.EndStream ); + + if( type == ETypes.Object ) + { + object obj = readObject( reader ); + + m_desObjects.Add( obj ); + } + else + { + Debug.Assert( type == ETypes.EndStream ); + + readObjects = false; + } + } + + foreach( Fixup fu in m_fixupList ) + { + //Fixup fix = m_fixups[ + + object obj = m_mapGUIDToObject[ fu.m_guid ]; + + if( obj != null ) + { + if( fu.m_fi != null ) + { + fu.m_fi.SetValue( fu.m_obj, obj ); + } + else + { + Debug.Assert( fu.m_index >= 0 ); + + object []array = (object [])fu.m_obj; + + array[ fu.m_index ] = obj; + } + } + else + { + Console.WriteLine( "Obj to ref is null." ); + } + } + + foreach( object obj in m_desObjects ) + { + if( typeof( IDeserializationCallback ).IsAssignableFrom( obj.GetType() ) ) + { + IDeserializationCallback desCB = (IDeserializationCallback)obj; + + if( desCB != null ) + { + desCB.OnDeserialization( this ); + } + } + } + + return objRoot; + } + + + + bool dispatchRead( StreamReader reader, object obj, Hashtable ht ) + { + + //Read the type + ETypes type = (ETypes)reader.ReadChar(); + + if( type == ETypes.EndObject ) + { + return false; + } + + int nameHash = reader.ReadInt32(); + + FieldInfo fi = (FieldInfo)ht[ nameHash ]; + + if( fi == null ) + { + Console.WriteLine( "Field no longer exists" ); + } + + try + { + switch( type ) + { + case ETypes.Array: + readArray( reader, obj, fi ); + break; + case ETypes.Int32: + readInt( reader, obj, fi ); + break; + case ETypes.Single: + readSingle( reader, obj, fi ); + break; + case ETypes.Double: + readDouble( reader, obj, fi ); + break; + case ETypes.Char: + readChar( reader, obj, fi ); + break; + case ETypes.Boolean: + readBool( reader, obj, fi ); + break; + case ETypes.String: + readString( reader, obj, fi ); + break; + case ETypes.Ref: + readRef( reader, obj, fi ); + break; + case ETypes.Object: + readObject( reader ); + break; + default: + Debug.Fail( "Unknown type on read." ); + break; + } + } + catch( Exception ex ) + { + Console.WriteLine( "Exception: " + ex.Message ); + Console.WriteLine( "Stack: " + ex.StackTrace ); + } + + + return true; + } + + object createObject( string objTypeName ) + { + Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies(); + + foreach( Assembly a in ass ) + { + Type t = a.GetType( objTypeName ); + + if( t != null ) + { + object obj = FormatterServices.GetUninitializedObject( t ); + + if( obj != null ) + { + return obj; + } + } + } + + return null; + } + + + object readObject( StreamReader reader ) + { + //ETypes type = (ETypes)reader.ReadChar(); + + //Debug.Assert( type == ETypes.Object, "Expecting type Object" ); + + string objTypeName = reader.ReadString(); + int objGUID = reader.ReadInt32(); + + try + { + object obj = createObject( objTypeName ); + + m_mapGUIDToObject[ objGUID ] = obj; + + ArrayList list = new ArrayList(); + Hashtable ht = new Hashtable(); + + if( obj != null ) + { + getAllFields( obj, list ); + + foreach( FieldInfo fi in list ) + { + ht[ fi.Name.GetHashCode() ] = fi; + } + } + + while( dispatchRead( reader, obj, ht ) ) + { + } + + return obj; + } + catch( Exception ex ) + { + Console.WriteLine( "Exception: " + ex.Message ); + } + + return null; + } + + void readArray( StreamReader reader, object obj, FieldInfo fi ) + { + int length = reader.ReadInt32(); + + if( length < 0 ) + { + if( fi == null ) return; + + fi.SetValue( obj, null ); + + return; + } + + object[] array = new object[length]; + + if( fi != null ) + { + fi.SetValue( obj, array ); + } + + for( int i=0; i() - { - return default( T ); - } - - private object DeserializeConcrete( XmlElement elem, Type type ) - { - string val = elem.GetAttribute( "v" ); - - if( !type.IsEnum ) + Type[] mm_types = new Type[1]; + private object GetDefault( Type t ) { - try + mm_types[0] = t; + + var fn = GetType().GetMethod( "GetDefaultGeneric" ).MakeGenericMethod( mm_types ); + + return fn.Invoke( this, null ); + } + + public T GetDefaultGeneric() + { + return default( T ); + } + + private object DeserializeConcrete( XmlElement elem, Type type ) + { + string val = elem.GetAttribute( "v" ); + + if( !type.IsEnum ) { - return s_conv.Convert( val, type ); + try + { + return s_conv.Convert( val, type ); + } + catch( Exception ) + { + return GetDefault( type ); + } } - catch( Exception ) + else { - return GetDefault( type ); + return Enum.Parse( type, val ); } - } - else - { - return Enum.Parse( type, val ); + } - } - - private XmlElement getNamedChild( XmlNodeList list, string name ) - { - foreach( XmlNode node in list ) + private XmlElement getNamedChild( XmlNodeList list, string name ) { - if( node.Name == name ) + foreach( XmlNode node in list ) { - return (XmlElement)node; + if( node.Name == name ) + { + return (XmlElement)node; + } } + + return null; } - return null; - } - - private Type FindType( string shortname ) - { - Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies(); - - foreach( Assembly a in ass ) + private Type FindType( string shortname ) { - Type t = a.GetType( shortname ); + Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies(); - if( t != null ) + foreach( Assembly a in ass ) { - return t; + Type t = a.GetType( shortname ); + + if( t != null ) + { + return t; + } } + + return null; } - return null; - } - - private Type[] mm_consType = new Type[ 2 ]; - private object[] mm_args = new object[ 2 ]; - private object DeserializeObject( XmlElement elem, Type type ) - { - string refString = elem.GetAttribute( "ref" ); - - int refInt = refString.Length > 0 ? Convert.ToInt32( refString ) : -1; - - var finalType = type; - if( elem.HasAttribute( "t" ) ) + private Type[] mm_consType = new Type[ 2 ]; + private object[] mm_args = new object[ 2 ]; + private object DeserializeObject( XmlElement elem, Type type ) { - var typename = elem.GetAttribute( "t" ); - finalType = FindType( typename ); + string refString = elem.GetAttribute( "ref" ); - if( finalType == null ) finalType = type; - } + int refInt = refString.Length > 0 ? Convert.ToInt32( refString ) : -1; - object obj = createObject( finalType, refInt ); - - if( obj is IList ) - { - var list = obj as IList; - - return DeserializeList( elem, type, list ); - } - - Type typeISerializable = typeof( ISerializable ); - - if( obj is ISerializable ) // type.IsSubclassOf( typeISerializable ) ) - { - XmlNodeList allChildren = elem.ChildNodes; - - //ISerializable ser = obj as ISerializable; - - var serInfo = new SerializationInfo( finalType, new FormatterConverter() ); - - //var serInfoForTypes = new SerializationInfo( type, new FormatterConverter() ); - - //ser.GetObjectData( serInfoForTypes, Context ); - - foreach( var objNode in allChildren ) + var finalType = type; + if( elem.HasAttribute( "t" ) ) { - var node = objNode as XmlElement; + var typename = elem.GetAttribute( "t" ); + finalType = FindType( typename ); - String name = node.Name; - - String childType = node.GetAttribute( "t" ); - - name = scr.TypeToIdentifier( name ); - - XmlElement childElem = getNamedChild( allChildren, name ); - - var des = Deserialize( childElem, childType ); - - serInfo.AddValue( name, des, des.GetType() ); + if( finalType == null ) + finalType = type; } - //ConstructorInfo[] allCons = obj.GetType().GetConstructors( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ); + object obj = createObject( finalType, refInt ); - //var serMem = FormatterServices.GetSerializableMembers( finalType ); - - //object objUn = FormatterServices.GetSafeUninitializedObject( finalType ); - - IDeserializationCallback objUnOnDeser = obj as IDeserializationCallback; - - mm_consType[ 0 ] = typeof( SerializationInfo ); - mm_consType[ 1 ] = typeof( StreamingContext ); - ConstructorInfo serCons = finalType.GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, mm_consType, null ); - - mm_args[0] = serInfo; - mm_args[1] = Context; - serCons.Invoke( obj, mm_args ); - - if( objUnOnDeser != null ) + if( obj is IList ) { - objUnOnDeser.OnDeserialization( objUnOnDeser ); + var list = obj as IList; + + return DeserializeList( elem, type, list ); } + Type typeISerializable = typeof( ISerializable ); + + if( obj is ISerializable ) // type.IsSubclassOf( typeISerializable ) ) + { + XmlNodeList allChildren = elem.ChildNodes; + + //ISerializable ser = obj as ISerializable; + + var serInfo = new SerializationInfo( finalType, new FormatterConverter() ); + + //var serInfoForTypes = new SerializationInfo( type, new FormatterConverter() ); + + //ser.GetObjectData( serInfoForTypes, Context ); + + foreach( var objNode in allChildren ) + { + var node = objNode as XmlElement; + + String name = node.Name; + + String childType = node.GetAttribute( "t" ); + + name = scr.TypeToIdentifier( name ); + + XmlElement childElem = getNamedChild( allChildren, name ); + + var des = Deserialize( childElem, childType ); + + serInfo.AddValue( name, des, des.GetType() ); + } + + //ConstructorInfo[] allCons = obj.GetType().GetConstructors( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ); + + //var serMem = FormatterServices.GetSerializableMembers( finalType ); + + //object objUn = FormatterServices.GetSafeUninitializedObject( finalType ); + + IDeserializationCallback objUnOnDeser = obj as IDeserializationCallback; + + mm_consType[0] = typeof( SerializationInfo ); + mm_consType[1] = typeof( StreamingContext ); + ConstructorInfo serCons = finalType.GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, mm_consType, null ); + + mm_args[0] = serInfo; + mm_args[1] = Context; + serCons.Invoke( obj, mm_args ); + + if( objUnOnDeser != null ) + { + objUnOnDeser.OnDeserialization( objUnOnDeser ); + } + /* ser.GetObjectData( serInfo, Context ); @@ -349,15 +352,15 @@ public class XmlFormatter2 : IFormatter */ } else - { - XmlNodeList allChildren = elem.ChildNodes; + { + XmlNodeList allChildren = elem.ChildNodes; var fields = scr.GetAllFields( type ); //MemberInfo[] miArr = FormatterServices.GetSerializableMembers( type, Context ); foreach( var childFi in fields ) - { + { String name = childFi.Name; @@ -366,367 +369,367 @@ public class XmlFormatter2 : IFormatter XmlElement childElem = getNamedChild( allChildren, name ); - if( childElem != null ) - { - object childObj = Deserialize( childElem, childFi.FieldType, obj ); + if( childElem != null ) + { + object childObj = Deserialize( childElem, childFi.FieldType, obj ); - childFi.SetValue( obj, childObj ); - } - else if( fields.Count == 1 ) - { - object childObj = Deserialize( elem, childFi.FieldType, obj ); + childFi.SetValue( obj, childObj ); + } + else if( fields.Count == 1 ) + { + object childObj = Deserialize( elem, childFi.FieldType, obj ); - childFi.SetValue( obj, childObj ); - } + childFi.SetValue( obj, childObj ); + } } - } - - return obj; - } - - private object DeserializeList( XmlElement elem, Type type, IList list ) - { - XmlNodeList arrNodeList = elem.ChildNodes; - - Type t = list.GetType(); - - Type[] genT = t.GetGenericArguments(); - - Debug.Assert( genT.Length == 1 ); - - for( int i = 0; i < arrNodeList.Count; ++i ) - { - if( arrNodeList.Item( i ) is XmlElement ) - { - XmlElement arrElem = (XmlElement)arrNodeList.Item( i ); - - list.Add( Deserialize( arrElem, genT[0] ) ); - } - } - - return list; - } - - private object DeserializeArray( XmlElement elem, Type type ) - { - Type typeElem = type.GetElementType(); - - string refString = elem.GetAttribute( "ref" ); - int refInt = refString.Length > 0 ? Convert.ToInt32( refString ) : -1; - - XmlNodeList arrNodeList = elem.ChildNodes; - - int length = arrNodeList.Count; - - Array arr = createArray( typeElem, refInt, length ); - - for( int i = 0; i < arr.Length; ++i ) - { - if( arrNodeList.Item( i ) is XmlElement ) - { - XmlElement arrElem = (XmlElement)arrNodeList.Item( i ); - - arr.SetValue( Deserialize( arrElem, typeElem ), i ); - } - } - - return arr; - } - - private object createObject( string typename, int refInt ) - { - Type type = Type.GetType( typename ); - - return createObject( type, refInt ); - } - - private object createObject( Type type, int refInt ) - { - TypeCode tc = Type.GetTypeCode( type ); - - if( m_cfg.datastructure == Datastructure.Full && refInt > 0 && m_alreadySerialized.ContainsKey( refInt ) ) - { - //lib.log.info( "Reusing object for {0}", refInt ); - return m_alreadySerialized[ refInt ]; - } - else - { - object obj = null; - - try - { - //Trying the nice way to creat objects first. - obj = Activator.CreateInstance( type ); - - } - catch( Exception ) - { - try - { - obj = System.Runtime.Serialization.FormatterServices.GetUninitializedObject( type ); - } - catch( Exception exInner ) - { - lib.Log.error( $"Got exception {exInner.Message} trying to make an uninitialized object" ); - } - - } - - if( obj == null ) - { - lib.Log.warn( $"Could not create object of type {type.Name}" ); - - return obj; - } - - if( m_cfg.datastructure == Datastructure.Full && refInt > 0 ) - { - m_alreadySerialized[refInt] = obj; } return obj; } - } - private Array createArray( string elemTypename, int refInt, int length ) - { - Type elemType = Type.GetType( elemTypename ); - - return createArray( elemType, refInt, length ); - } - - private Array createArray( Type elemType, int refInt, int length ) - { - TypeCode elemTC = Type.GetTypeCode( elemType ); - - if( m_cfg.datastructure == Datastructure.Full && refInt > 0 && m_alreadySerialized.ContainsKey( refInt ) ) + private object DeserializeList( XmlElement elem, Type type, IList list ) { - return (Array)m_alreadySerialized[ refInt ]; - } - else - { - Array arr = Array.CreateInstance( elemType, length ) ; + XmlNodeList arrNodeList = elem.ChildNodes; - if( m_cfg.datastructure == Datastructure.Full ) + Type t = list.GetType(); + + Type[] genT = t.GetGenericArguments(); + + Debug.Assert( genT.Length == 1 ); + + for( int i = 0; i < arrNodeList.Count; ++i ) { - m_alreadySerialized[ refInt ] = arr; + if( arrNodeList.Item( i ) is XmlElement ) + { + XmlElement arrElem = (XmlElement)arrNodeList.Item( i ); + list.Add( Deserialize( arrElem, genT[0] ) ); + } + } + + return list; + } + + private object DeserializeArray( XmlElement elem, Type type ) + { + Type typeElem = type.GetElementType(); + + string refString = elem.GetAttribute( "ref" ); + int refInt = refString.Length > 0 ? Convert.ToInt32( refString ) : -1; + + XmlNodeList arrNodeList = elem.ChildNodes; + + int length = arrNodeList.Count; + + Array arr = createArray( typeElem, refInt, length ); + + for( int i = 0; i < arr.Length; ++i ) + { + if( arrNodeList.Item( i ) is XmlElement ) + { + XmlElement arrElem = (XmlElement)arrNodeList.Item( i ); + + arr.SetValue( Deserialize( arrElem, typeElem ), i ); + } } return arr; } - } - private ObjectIDGenerator m_objectID = new ObjectIDGenerator(); - private Dictionary m_alreadySerialized = new Dictionary(); - - #endregion - - #region Serialize - - private string getTypeName( Type type ) - { - //Assembly ass = type.Assembly; - - //string assName = ass.GetName().Name; - - return type.FullName; // + ", " + assName; - } - - public void Serialize( Stream stream, object root ) - { - //lib.log.info( "Serialize( Stream stream, object root ) {0} {1}", m_rndVal, m_alreadySerialized.Count ); - - m_alreadySerialized.Clear(); - m_objectID = new ObjectIDGenerator(); - - XmlTextWriter writer = new XmlTextWriter( stream, System.Text.Encoding.ASCII ); - - writer.Formatting = Formatting.Indented; - - Serialize( writer, root ); - - //Rely on the parent closing the stream. - //writer.Close(); - writer.Flush(); - - //lib.log.info( "Serialize END ( Stream stream, object root ) {0} {1}", m_rndVal, m_alreadySerialized.Count ); - } - - private void Serialize( XmlWriter writer, object root ) - { - //writer.WriteStartDocument(); - Serialize( writer, root, "root", true ); - //writer.WriteEndDocument(); - } - - private void Serialize( XmlWriter writer, object root, string name, bool forceType ) - { - writer.WriteStartElement( name ); - - if( root != null ) + private object createObject( string typename, int refInt ) { - Type type = root.GetType(); + Type type = Type.GetType( typename ); - TypeCode typeCode = Type.GetTypeCode( type ); + return createObject( type, refInt ); + } - if( typeCode != TypeCode.Object ) + private object createObject( Type type, int refInt ) + { + TypeCode tc = Type.GetTypeCode( type ); + + if( m_cfg.datastructure == Datastructure.Full && refInt > 0 && m_alreadySerialized.ContainsKey( refInt ) ) { - SerializeConcrete( writer, root, forceType ); + //lib.log.info( "Reusing object for {0}", refInt ); + return m_alreadySerialized[refInt]; } else { - if( !type.IsArray ) + object obj = null; + + try { - SerializeObject( writer, root ); + //Trying the nice way to creat objects first. + obj = Activator.CreateInstance( type ); + + } + catch( Exception ) + { + try + { + obj = System.Runtime.Serialization.FormatterServices.GetUninitializedObject( type ); + } + catch( Exception exInner ) + { + lib.Log.error( $"Got exception {exInner.Message} trying to make an uninitialized object" ); + } + + } + + if( obj == null ) + { + lib.Log.warn( $"Could not create object of type {type.Name}" ); + + return obj; + } + + if( m_cfg.datastructure == Datastructure.Full && refInt > 0 ) + { + m_alreadySerialized[refInt] = obj; + } + + return obj; + } + } + + private Array createArray( string elemTypename, int refInt, int length ) + { + Type elemType = Type.GetType( elemTypename ); + + return createArray( elemType, refInt, length ); + } + + private Array createArray( Type elemType, int refInt, int length ) + { + TypeCode elemTC = Type.GetTypeCode( elemType ); + + if( m_cfg.datastructure == Datastructure.Full && refInt > 0 && m_alreadySerialized.ContainsKey( refInt ) ) + { + return (Array)m_alreadySerialized[refInt]; + } + else + { + Array arr = Array.CreateInstance( elemType, length ) ; + + if( m_cfg.datastructure == Datastructure.Full ) + { + m_alreadySerialized[refInt] = arr; + + } + + return arr; + } + } + + private ObjectIDGenerator m_objectID = new ObjectIDGenerator(); + private Dictionary m_alreadySerialized = new Dictionary(); + + #endregion + + #region Serialize + + private string getTypeName( Type type ) + { + //Assembly ass = type.Assembly; + + //string assName = ass.GetName().Name; + + return type.FullName; // + ", " + assName; + } + + public void Serialize( Stream stream, object root ) + { + //lib.log.info( "Serialize( Stream stream, object root ) {0} {1}", m_rndVal, m_alreadySerialized.Count ); + + m_alreadySerialized.Clear(); + m_objectID = new ObjectIDGenerator(); + + XmlTextWriter writer = new XmlTextWriter( stream, System.Text.Encoding.ASCII ); + + writer.Formatting = Formatting.Indented; + + Serialize( writer, root ); + + //Rely on the parent closing the stream. + //writer.Close(); + writer.Flush(); + + //lib.log.info( "Serialize END ( Stream stream, object root ) {0} {1}", m_rndVal, m_alreadySerialized.Count ); + } + + private void Serialize( XmlWriter writer, object root ) + { + //writer.WriteStartDocument(); + Serialize( writer, root, "root", true ); + //writer.WriteEndDocument(); + } + + private void Serialize( XmlWriter writer, object root, string name, bool forceType ) + { + writer.WriteStartElement( name ); + + if( root != null ) + { + Type type = root.GetType(); + + TypeCode typeCode = Type.GetTypeCode( type ); + + if( typeCode != TypeCode.Object ) + { + SerializeConcrete( writer, root, forceType ); } else { - SerializeArray( writer, root ); + if( !type.IsArray ) + { + SerializeObject( writer, root ); + } + else + { + SerializeArray( writer, root ); + } } } - } - else - { - writer.WriteAttributeString( "v", "null" ); - } - - writer.WriteEndElement(); - } - - private void SerializeConcrete( XmlWriter writer, object root, bool forceType ) - { - //TODO: Only write this out if debugging. - if( forceType ) - { - writer.WriteAttributeString( "t", getTypeName( root.GetType() ) ); - } - writer.WriteAttributeString( "v", root.ToString() ); - } - - private void SerializeObject( XmlWriter writer, object root ) - { - writer.WriteAttributeString( "t", getTypeName( root.GetType() ) ); - - /* - if( root is IList ) - { - var list = root as IList; - - Type t = root.GetType(); - - Type[] genT = t.GetGenericArguments(); - } - */ - - bool first; - - long refInt = m_objectID.GetId( root, out first ); - - if( m_cfg.datastructure == Datastructure.Full ) - { - writer.WriteAttributeString( "ref", refInt.ToString() ); - - } - - if( first ) - { - if( m_cfg.datastructure == Datastructure.Full ) + else { - m_alreadySerialized[ refInt ] = root; + writer.WriteAttributeString( "v", "null" ); } - Type type = root.GetType(); + writer.WriteEndElement(); + } - //* - Type typeISerializable = typeof( ISerializable ); - - if( root is ISerializable ) // type.IsSubclassOf( typeISerializable ) ) + private void SerializeConcrete( XmlWriter writer, object root, bool forceType ) + { + //TODO: Only write this out if debugging. + if( forceType ) { - ISerializable ser = root as ISerializable; + writer.WriteAttributeString( "t", getTypeName( root.GetType() ) ); + } + writer.WriteAttributeString( "v", root.ToString() ); + } - var serInfo = new SerializationInfo( type, new FormatterConverter() ); + private void SerializeObject( XmlWriter writer, object root ) + { + writer.WriteAttributeString( "t", getTypeName( root.GetType() ) ); - ser.GetObjectData( serInfo, Context ); + /* + if( root is IList ) + { + var list = root as IList; - //var serEnum = ; + Type t = root.GetType(); - foreach( var serMember in serInfo ) + Type[] genT = t.GetGenericArguments(); + } + */ + + bool first; + + long refInt = m_objectID.GetId( root, out first ); + + if( m_cfg.datastructure == Datastructure.Full ) + { + writer.WriteAttributeString( "ref", refInt.ToString() ); + + } + + if( first ) + { + if( m_cfg.datastructure == Datastructure.Full ) { - String name = serMember.Name; + m_alreadySerialized[refInt] = root; + } + + Type type = root.GetType(); + + //* + Type typeISerializable = typeof( ISerializable ); + + if( root is ISerializable ) // type.IsSubclassOf( typeISerializable ) ) + { + ISerializable ser = root as ISerializable; + + var serInfo = new SerializationInfo( type, new FormatterConverter() ); + + ser.GetObjectData( serInfo, Context ); + + //var serEnum = ; + + foreach( var serMember in serInfo ) + { + String name = serMember.Name; name = scr.TypeToIdentifier( name ); Serialize( writer, serMember.Value, name, true ); - } - - //var sc = new SerializationContext( - - //ser.GetObjectData( - } - else - //*/ - { - var fields = scr.GetAllFields( type ); - - //MemberInfo[] miArr = FormatterServices.GetSerializableMembers( type, Context ); - - foreach( var childFi in fields ) - { - - object[] objs = childFi.GetCustomAttributes( typeof( NonSerializedAttribute ), true ); - - if( objs.Length > 0 ) - { - continue; } - String name = childFi.Name; + //var sc = new SerializationContext( + + //ser.GetObjectData( + } + else + //*/ + { + var fields = scr.GetAllFields( type ); + + //MemberInfo[] miArr = FormatterServices.GetSerializableMembers( type, Context ); + + foreach( var childFi in fields ) + { + + object[] objs = childFi.GetCustomAttributes( typeof( NonSerializedAttribute ), true ); + + if( objs.Length > 0 ) + { + continue; + } + + String name = childFi.Name; name = scr.TypeToIdentifier( name ); Serialize( writer, childFi.GetValue( root ), name, false ); + } } } } - } - private void SerializeArray( XmlWriter writer, object root ) - { - Array arr = (Array)root; - - Type typeElem = arr.GetType().GetElementType(); - - Type type = root.GetType(); - - writer.WriteAttributeString( "t", getTypeName( type ) ); - - bool first; - - long refInt = m_objectID.GetId( root, out first ); - - if( m_cfg.datastructure == Datastructure.Full ) + private void SerializeArray( XmlWriter writer, object root ) { - writer.WriteAttributeString( "ref", refInt.ToString() ); - } + Array arr = (Array)root; + + Type typeElem = arr.GetType().GetElementType(); + + Type type = root.GetType(); + + writer.WriteAttributeString( "t", getTypeName( type ) ); + + bool first; + + long refInt = m_objectID.GetId( root, out first ); - if( first ) - { if( m_cfg.datastructure == Datastructure.Full ) { - m_alreadySerialized[ refInt ] = root; + writer.WriteAttributeString( "ref", refInt.ToString() ); } - - for( int i = 0; i < arr.Length; ++i ) + if( first ) { - Serialize( writer, arr.GetValue( i ), "i" + i.ToString(), false ); + if( m_cfg.datastructure == Datastructure.Full ) + { + m_alreadySerialized[refInt] = root; + } + + + for( int i = 0; i < arr.Length; ++i ) + { + Serialize( writer, arr.GetValue( i ), "i" + i.ToString(), false ); + } } } + #endregion } - #endregion -} } diff --git a/att/CanBeNullAttribute.cs b/att/CanBeNullAttribute.cs index ca23334..6fe41c1 100644 --- a/att/CanBeNullAttribute.cs +++ b/att/CanBeNullAttribute.cs @@ -27,25 +27,25 @@ using System; namespace att { - /// - /// Indicates that the value of the marked element could be null sometimes, so the check for null - /// is necessary before its usage. - /// - /// - /// - /// [CanBeNull] object Test() => null; - /// - /// void UseTest() { - /// var p = Test(); - /// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException' - /// } - /// - /// - [AttributeUsage( - AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | - AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | - AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] - public sealed class CanBeNullAttribute : Attribute - { - } + /// + /// Indicates that the value of the marked element could be null sometimes, so the check for null + /// is necessary before its usage. + /// + /// + /// + /// [CanBeNull] object Test() => null; + /// + /// void UseTest() { + /// var p = Test(); + /// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException' + /// } + /// + /// + [AttributeUsage( + AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | + AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | + AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter )] + public sealed class CanBeNullAttribute : Attribute + { + } } diff --git a/att/NotNullAttribute.cs b/att/NotNullAttribute.cs index 60afed4..b0ca3b4 100644 --- a/att/NotNullAttribute.cs +++ b/att/NotNullAttribute.cs @@ -5,21 +5,21 @@ using System; namespace att { - /// - /// Indicates that the value of the marked element could never be null. - /// - /// - /// - /// [NotNull] object Foo() { - /// return null; // Warning: Possible 'null' assignment - /// } - /// - /// - [AttributeUsage( - AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | - AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | - AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] - public sealed class NotNullAttribute : Attribute - { - } + /// + /// Indicates that the value of the marked element could never be null. + /// + /// + /// + /// [NotNull] object Foo() { + /// return null; // Warning: Possible 'null' assignment + /// } + /// + /// + [AttributeUsage( + AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | + AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | + AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter )] + public sealed class NotNullAttribute : Attribute + { + } } diff --git a/mod/Modules.cs b/mod/Modules.cs index 4b455fd..0e82f4b 100644 --- a/mod/Modules.cs +++ b/mod/Modules.cs @@ -9,79 +9,79 @@ using System.Reflection; namespace mod { -[Serializable] -public class Config : lib.Config -{ - public String name = "Generic"; -} - -public class View -{ -} - -public class Base -{ - public Config Cfg { get { return m_cfg; } } - - public Base( Config cfg ) + [Serializable] + public class Config : lib.Config { - m_cfg = cfg; + public String name = "Generic"; } - private Config m_cfg; -} - - -[Serializable] -public class FluidConfig : Config -{ - public String type = "none"; -} - - -public class FluidBase : Base -{ - public new FluidConfig Cfg { get { return (FluidConfig)base.Cfg; } } - - public FluidBase( FluidConfig cfg ) - : base( cfg ) + public class View { } -} - - - - - - - - - - - - - - - -[Serializable] -public class SystemConfig : Config -{ - public String type = "none"; -} - - -public class System -{ - public SystemConfig Cfg { get { return m_cfg; } } - - public System( SystemConfig cfg ) + public class Base { - m_cfg = cfg; + public Config Cfg { get { return m_cfg; } } + + public Base( Config cfg ) + { + m_cfg = cfg; + } + + private Config m_cfg; } - private SystemConfig m_cfg; -} + + [Serializable] + public class FluidConfig : Config + { + public String type = "none"; + } + + + public class FluidBase : Base + { + public new FluidConfig Cfg { get { return (FluidConfig)base.Cfg; } } + + public FluidBase( FluidConfig cfg ) + : base( cfg ) + { + } + } + + + + + + + + + + + + + + + + + [Serializable] + public class SystemConfig : Config + { + public String type = "none"; + } + + + public class System + { + public SystemConfig Cfg { get { return m_cfg; } } + + public System( SystemConfig cfg ) + { + m_cfg = cfg; + } + + private SystemConfig m_cfg; + } } diff --git a/res/Resource.cs b/res/Resource.cs index 82882a3..2f8eb53 100644 --- a/res/Resource.cs +++ b/res/Resource.cs @@ -49,7 +49,7 @@ namespace res private string m_filename; } - + [Serializable] public class Ref : Ref where T : class { @@ -156,14 +156,14 @@ namespace res var lh = new LoadHolder( loader ); - ImmutableInterlocked.TryAdd( ref Resource.mgr.m_loaders, typeof(T), lh ); + ImmutableInterlocked.TryAdd( ref Resource.mgr.m_loaders, typeof( T ), lh ); } //Register all subclasses of a particular type //???? Should we just always do this? static public void registerSub( Type baseType ) { - + Type[] typeParams = new Type[1]; foreach( var mi in baseType.GetMethods() ) { @@ -194,7 +194,7 @@ namespace res } } } - return; + return; } } } @@ -244,7 +244,8 @@ namespace res { if( ResCache.s_cache.TryGetValue( filename, out var wr ) ) { - if( wr.TryGetTarget(out var v) ) return v; + if( wr.TryGetTarget( out var v ) ) + return v; lib.Log.info( $"{filename} was in cache, but its been dropped, reloading." ); } @@ -275,7 +276,7 @@ namespace res if( ImmutableInterlocked.TryAdd( ref s_loading, filename, evtNew ) ) { - if( Resource.mgr.m_loaders.TryGetValue( typeof(T), out var loaderGen ) ) + if( Resource.mgr.m_loaders.TryGetValue( typeof( T ), out var loaderGen ) ) { var loader = loaderGen as LoadHolder; @@ -302,7 +303,7 @@ namespace res } else { - lib.Log.error( $"Loader could not be found for type {typeof(T)}" ); + lib.Log.error( $"Loader could not be found for type {typeof( T )}" ); return ResCache.s_default; }