Reformat files

This commit is contained in:
Marc Hernandez 2019-07-12 01:02:29 -07:00
parent dd21ff0023
commit 30f3aa983b
21 changed files with 3123 additions and 3086 deletions

View File

@ -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;

244
Config.cs
View File

@ -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<Config>( load );
res.Mgr.registerSub(typeof(Config));
s_cfg = Config.load<ConfigCfg>( filename );
public readonly bool writeOutTemplateFiles = true;
}
#region SaveLoad
/*
static public res.Ref<Config> res_load( string filename )
[Serializable]
public class Config
{
return new res.Ref<Config>( filename, load( filename ) );
}
*/
/*
static public Config Load( string filename )
{
return null;
}
*/
static public T res_load<T>( string filename ) where T : Config
{
return load<T>( 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<Config>( load );
res.Mgr.registerSub( typeof( Config ) );
s_cfg = Config.load<ConfigCfg>( filename );
}
static public Config load( string filename )
{
FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read );
#region SaveLoad
/*
static public res.Ref<Config> res_load( string filename )
{
return new res.Ref<Config>( filename, load( filename ) );
}
*/
XmlFormatter2 formatter = new XmlFormatter2();
static public T res_load<T>( string filename ) where T : Config
{
return load<T>( 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<T>( 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<T>( 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; }
}
}

141
Conn.cs
View File

@ -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;
}

View File

@ -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<TKey, TVal> 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}" ) );
}
}

14
Id.cs
View File

@ -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 )
{

95
Log.cs
View File

@ -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>( T value, string falseString, string trueString = "", T notExpectedValue = default(T) )
static public void expected<T>( 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();
}
}

View File

@ -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;
}
}

76
Pos.cs
View File

@ -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;
}
}
}
}

14
Scr.cs
View File

@ -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<T> m_en;
Predicate<T> m_pred;
IEnumerator<T> m_en;
Predicate<T> m_pred;
}
@ -181,7 +182,8 @@ static public class scr
public static ImmutableList<PropertyInfo> 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<PropertyInfo>();

View File

@ -10,148 +10,156 @@ using System.Security.Permissions;
namespace lib
{
[Serializable]
public class SerializableDictionary<TKey, TVal> : Dictionary<TKey, TVal>, 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<TKey, TVal> : Dictionary<TKey, TVal>, 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<TKey,TVal> dictionary)
: base(dictionary)
{
}
public SerializableDictionary( IDictionary<TKey, TVal> dictionary )
: base( dictionary )
{
}
public SerializableDictionary(IEqualityComparer<TKey> comparer)
: base(comparer)
{
}
public SerializableDictionary( IEqualityComparer<TKey> comparer )
: base( comparer )
{
}
public SerializableDictionary(int capacity)
: base(capacity)
{
}
public SerializableDictionary( int capacity )
: base( capacity )
{
}
public SerializableDictionary(IDictionary<TKey,TVal> dictionary, IEqualityComparer<TKey> comparer)
: base(dictionary, comparer)
{
}
public SerializableDictionary( IDictionary<TKey, TVal> dictionary, IEqualityComparer<TKey> comparer )
: base( dictionary, comparer )
{
}
public SerializableDictionary(int capacity, IEqualityComparer<TKey> comparer)
: base(capacity, comparer)
{
}
public SerializableDictionary( int capacity, IEqualityComparer<TKey> 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<TKey, TVal> kvp = (KeyValuePair<TKey, TVal>)info.GetValue(String.Format( $"Item{i}" ), typeof(KeyValuePair<TKey, TVal>));
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<TKey, TVal> kvp = (KeyValuePair<TKey, TVal>)info.GetValue(String.Format( $"Item{i}" ), typeof(KeyValuePair<TKey, TVal>));
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<TKey, TVal> kvp in this) {
info.AddValue(String.Format( $"Item{itemIdx}" ), kvp, typeof(KeyValuePair<TKey, TVal>));
itemIdx++;
}
}
[SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )]
void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context )
{
info.AddValue( "ItemCount", this.Count );
int itemIdx = 0;
foreach( KeyValuePair<TKey, TVal> kvp in this )
{
info.AddValue( String.Format( $"Item{itemIdx}" ), kvp, typeof( KeyValuePair<TKey, TVal> ) );
itemIdx++;
}
}
#endregion
#region IXmlSerializable Members
#endregion
#region IXmlSerializable Members
void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
{
//writer.WriteStartElement(DictionaryNodeName);
foreach (KeyValuePair<TKey, TVal> 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<TKey, TVal> 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
}
}

620
Timer.cs
View File

@ -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);
}
}
}
/// <summary>
/// MicroTimer class
/// </summary>
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();
}
}
/// <summary>
/// MicroTimer Event Argument class
/// </summary>
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 );
}
}
}
/// <summary>
/// MicroTimer class
/// </summary>
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();
}
}
/// <summary>
/// MicroTimer Event Argument class
/// </summary>
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; }
}
}
}

View File

@ -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;
}
}

View File

@ -27,139 +27,139 @@ using System.Runtime.CompilerServices;
namespace lib
{
/// <summary>
/// Utility class.
/// </summary>
internal sealed class Interop
{
public static T Pin<T>(ref T source) where T : struct
{
throw new NotImplementedException();
}
/// <summary>
/// Utility class.
/// </summary>
internal sealed class Interop
{
public static T Pin<T>( ref T source ) where T : struct
{
throw new NotImplementedException();
}
public static T IncrementPinned<T>(T source) where T : struct
{
throw new NotImplementedException();
}
public static T IncrementPinned<T>( T source ) where T : struct
{
throw new NotImplementedException();
}
public static T AddPinned<T>(T source, int offset) where T : struct
{
throw new NotImplementedException();
}
public static T AddPinned<T>( T source, int offset ) where T : struct
{
throw new NotImplementedException();
}
public static void Pin<T>(T data) where T : class
{
throw new NotImplementedException();
}
public static void Pin<T>( T data ) where T : class
{
throw new NotImplementedException();
}
public static unsafe void* Fixed<T>(ref T data)
{
throw new NotImplementedException();
}
public static unsafe void* Fixed<T>( ref T data )
{
throw new NotImplementedException();
}
public static unsafe void* FixedOut<T>(out T data)
{
throw new NotImplementedException();
}
public static unsafe void* FixedOut<T>( out T data )
{
throw new NotImplementedException();
}
public static unsafe void* Fixed<T>(T[] data)
{
throw new NotImplementedException();
}
public static unsafe void* Fixed<T>( T[] data )
{
throw new NotImplementedException();
}
public static unsafe void* Cast<T>(ref T data) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void* Cast<T>( ref T data ) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void* CastOut<T>(out T data) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void* CastOut<T>( out T data ) where T : struct
{
throw new NotImplementedException();
}
public static TCAST[] CastArray<TCAST, T>(T[] arrayData)
where T : struct
where TCAST : struct
{
throw new NotImplementedException();
}
public static TCAST[] CastArray<TCAST, T>( 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<T>(void* pSrc, ref T data) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void* Read<T>( void* pSrc, ref T data ) where T : struct
{
throw new NotImplementedException();
}
public static unsafe T ReadInline<T>(void* pSrc) where T : struct
{
throw new NotImplementedException();
}
public static unsafe T ReadInline<T>( void* pSrc ) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void WriteInline<T>(void* pDest, ref T data) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void WriteInline<T>( void* pDest, ref T data ) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void CopyInline<T>(ref T data, void* pSrc) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void CopyInline<T>( ref T data, void* pSrc ) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void CopyInline<T>(void* pDest, ref T srcData)
{
throw new NotImplementedException();
}
public static unsafe void CopyInline<T>( void* pDest, ref T srcData )
{
throw new NotImplementedException();
}
public static unsafe void CopyInlineOut<T>(out T data, void* pSrc)
{
throw new NotImplementedException();
}
public static unsafe void CopyInlineOut<T>( out T data, void* pSrc )
{
throw new NotImplementedException();
}
public static unsafe void* ReadOut<T>(void* pSrc, out T data) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void* ReadOut<T>( void* pSrc, out T data ) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void* Read<T>(void* pSrc, T[] data, int offset, int count) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void* Read<T>( void* pSrc, T[] data, int offset, int count ) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void* Read2D<T>(void* pSrc, T[,] data, int offset, int count) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void* Read2D<T>( void* pSrc, T[,] data, int offset, int count ) where T : struct
{
throw new NotImplementedException();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int SizeOf<T>()
{
throw new NotImplementedException();
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static int SizeOf<T>()
{
throw new NotImplementedException();
}
public static unsafe void* Write<T>(void* pDest, ref T data) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void* Write<T>( void* pDest, ref T data ) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void* Write<T>(void* pDest, T[] data, int offset, int count) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void* Write<T>( void* pDest, T[] data, int offset, int count ) where T : struct
{
throw new NotImplementedException();
}
public static unsafe void* Write2D<T>(void* pDest, T[,] data, int offset, int count) where T : struct
{
throw new NotImplementedException();
}
}
public static unsafe void* Write2D<T>( void* pDest, T[,] data, int offset, int count ) where T : struct
{
throw new NotImplementedException();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -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<length; ++i )
for( int i = 0; i < length; ++i )
{
int val = reader.ReadInt32();
//m_fixups[ val ] = new Fixup( obj, fi );
if( fi != null )
{
m_fixupList.Add( new Fixup( val, array, i ) );
}
}
}
void readRef( BinaryReader reader, object obj, FieldInfo fi )
{
int val = reader.ReadInt32();
//m_fixups[ val ] = new Fixup( obj, fi );
m_fixupList.Add( new Fixup( val, obj, fi ) );
}
void readInt( BinaryReader reader, object obj, FieldInfo fi )
{
int val = reader.ReadInt32();
if( fi == null ) return;
if( fi == null )
return;
if( !fi.FieldType.IsEnum )
{
fi.SetValue( obj, val );
@ -596,56 +598,61 @@ namespace lib
object enumVal = Enum.Parse( fi.FieldType, val.ToString() );
fi.SetValue( obj, Convert.ChangeType( enumVal, fi.FieldType ) );
}
}
void readSingle( BinaryReader reader, object obj, FieldInfo fi )
{
float val = reader.ReadSingle();
if( fi == null ) return;
if( fi == null )
return;
fi.SetValue( obj, val );
}
void readDouble( BinaryReader reader, object obj, FieldInfo fi )
{
double val = reader.ReadDouble();
if( fi == null ) return;
if( fi == null )
return;
fi.SetValue( obj, val );
}
void readChar( BinaryReader reader, object obj, FieldInfo fi )
{
char val = reader.ReadChar();
if( fi == null ) return;
if( fi == null )
return;
fi.SetValue( obj, val );
}
void readString( BinaryReader reader, object obj, FieldInfo fi )
{
string val = reader.ReadString();
if( fi == null ) return;
if( fi == null )
return;
fi.SetValue( obj, val );
}
void readBool( BinaryReader reader, object obj, FieldInfo fi )
{
bool val = reader.ReadBoolean();
if( fi == null ) return;
if( fi == null )
return;
fi.SetValue( obj, val );
}
#endregion Deserialize
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -27,25 +27,25 @@ using System;
namespace att
{
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes, so the check for <c>null</c>
/// is necessary before its usage.
/// </summary>
/// <example>
/// <code>
/// [CanBeNull] object Test() => null;
///
/// void UseTest() {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code>
/// </example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)]
public sealed class CanBeNullAttribute : Attribute
{
}
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes, so the check for <c>null</c>
/// is necessary before its usage.
/// </summary>
/// <example>
/// <code>
/// [CanBeNull] object Test() => null;
///
/// void UseTest() {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code>
/// </example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter )]
public sealed class CanBeNullAttribute : Attribute
{
}
}

View File

@ -5,21 +5,21 @@ using System;
namespace att
{
/// <summary>
/// Indicates that the value of the marked element could never be <c>null</c>.
/// </summary>
/// <example>
/// <code>
/// [NotNull] object Foo() {
/// return null; // Warning: Possible 'null' assignment
/// }
/// </code>
/// </example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)]
public sealed class NotNullAttribute : Attribute
{
}
/// <summary>
/// Indicates that the value of the marked element could never be <c>null</c>.
/// </summary>
/// <example>
/// <code>
/// [NotNull] object Foo() {
/// return null; // Warning: Possible 'null' assignment
/// }
/// </code>
/// </example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter )]
public sealed class NotNullAttribute : Attribute
{
}
}

View File

@ -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;
}
}

View File

@ -49,7 +49,7 @@ namespace res
private string m_filename;
}
[Serializable]
public class Ref<T> : Ref where T : class
{
@ -156,14 +156,14 @@ namespace res
var lh = new LoadHolder<T>( 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<T>.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<T>;
@ -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<T>.s_default;
}