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_lastTime = m_timer.Current;
m_totalMillis = timeOffset; m_totalMillis = timeOffset;
m_totalSeconds= (double)m_totalMillis / 1000.0; m_totalSeconds = (double)m_totalMillis / 1000.0;
} }
public void tick() public void tick()
{ {
long current = m_timer.Current; 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_dtSeconds = (double)m_dtMillis / 1000.0;
m_totalMillis += m_dtMillis; m_totalMillis += m_dtMillis;
m_totalSeconds = (double)m_totalMillis / 1000.0; m_totalSeconds = (double)m_totalMillis / 1000.0;
m_lastTime = current; m_lastTime = current;
@ -34,8 +34,8 @@ namespace lib
public int dtMs { get { return m_dtMillis; } } public int dtMs { get { return m_dtMillis; } }
public double dtSec { get { return m_dtSeconds; } } public double dtSec { get { return m_dtSeconds; } }
public long ms { get { return m_totalMillis; } } public long ms { get { return m_totalMillis; } }
public double sec{ get { return m_totalSeconds; } } public double sec { get { return m_totalSeconds; } }
Timer m_timer; Timer m_timer;

244
Config.cs
View File

@ -6,167 +6,167 @@ using System.Reflection;
namespace lib namespace lib
{ {
public class DescAttribute : Attribute public class DescAttribute : Attribute
{
public string Desc { get; private set; }
public DescAttribute( string desc )
{ {
Desc = desc; public string Desc { get; private set; }
public DescAttribute( string desc )
{
Desc = desc;
}
} }
}
[Serializable] [Serializable]
public class ConfigCfg : Config public class ConfigCfg : Config
{
public readonly bool writeOutTemplateFiles = true;
}
[Serializable]
public class Config
{
/*
static public Config Load( string filename )
{ {
return null; public readonly bool writeOutTemplateFiles = true;
}
*/
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 );
} }
#region SaveLoad
/* [Serializable]
static public res.Ref<Config> res_load( string filename ) 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 static ConfigCfg s_cfg = new ConfigCfg();
{
return load<T>( filename );
}
/* static public void startup( string filename )
static public ResRefConfig res_load( string filename, Type t ) {
{ res.Mgr.register<Config>( load );
return new ResRefConfig( filename, load( filename, t ) ); res.Mgr.registerSub( typeof( Config ) );
}
*/ s_cfg = Config.load<ConfigCfg>( filename );
}
static public Config load( string filename ) #region SaveLoad
{ /*
FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read ); 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 static public Config load( string filename )
{
return (T)load( filename, typeof( T ) );
}
static public Config load( string filename, Type t )
{
Config cfg = null;
try
{ {
FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read ); FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read );
XmlFormatter2 formatter = new XmlFormatter2(); 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 ]; return (T)load( filename, typeof( T ) );
object[] parms = new object[ 0 ]; }
//types[ 0 ] = typeof( string ); static public Config load( string filename, Type t )
//parms[ 0 ] = filename; {
Config cfg = null;
ConstructorInfo cons = t.GetConstructor( types );
try 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 ) ConstructorInfo cons = t.GetConstructor( types );
{
var templateFile = $"templates/{filename}";
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,98 +12,99 @@ namespace lib
public interface IProcess 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 )
{ {
m_socket = sock; void process( object obj );
sock.NoDelay = true;
m_streamNet = new NetworkStream( m_socket );
m_proc = proc;
} }
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(); public Conn( Socket sock, IProcess proc )
try
{ {
obj = formatter.Deserialize( stream ); m_socket = sock;
}
catch( System.Xml.XmlException ex ) sock.NoDelay = true;
{
lib.Log.error( $"Outer Exception {ex.Message}" ); m_streamNet = new NetworkStream( m_socket );
m_proc = proc;
} }
return obj; public object recieveObject()
}
public void send( object obj )
{
var formatter = new XmlFormatter2();
try
{ {
var ms = new MemoryStream( 1024 ); return recieveObject( Stream );
formatter.Serialize( ms, obj ); }
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 ); //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 data {str} of length {ms.Position}" );
//lib.Log.info( $"Sent {obj}" ); //lib.Log.info( $"Sent {obj}" );
byte[] byteSize = BitConverter.GetBytes( (uint)ms.Position ); byte[] byteSize = BitConverter.GetBytes( (uint)ms.Position );
m_streamNet.Write( byteSize, 0, 4 ); m_streamNet.Write( byteSize, 0, 4 );
m_streamNet.Write( ms.GetBuffer(), 0, (int)ms.Position ); 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}" ); if( m_proc != null )
throw; 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(); Type[] types = dict.GetType().GetGenericArguments();
xmlWriter.WriteAttributeString( "keyType", types[ 0 ].FullName ); xmlWriter.WriteAttributeString( "keyType", types[0].FullName );
xmlWriter.WriteAttributeString( "valType", types[ 1 ].FullName ); xmlWriter.WriteAttributeString( "valType", types[1].FullName );
foreach( KeyValuePair<TKey, TVal> kvp in dict ) foreach( KeyValuePair<TKey, TVal> kvp in dict )
{ {
@ -135,15 +135,15 @@ namespace lib
{ {
if( node.Attributes != null ) if( node.Attributes != null )
{ {
args[ 0 ] = node.GetAttribute( "key" ); args[0] = node.GetAttribute( "key" );
TKey key = (TKey)keyMI.Invoke( null, args ); TKey key = (TKey)keyMI.Invoke( null, args );
args[ 0 ] = node.GetAttribute( "value" ); args[0] = node.GetAttribute( "value" );
TVal val = (TVal)valMI.Invoke( null, args ); TVal val = (TVal)valMI.Invoke( null, args );
dict[ key ] = val; dict[key] = val;
} }
else else
{ {

61
Log.cs
View File

@ -15,26 +15,26 @@ namespace lib
[Flags] [Flags]
public enum LogTypeNew public enum LogTypeNew
{ {
Invalid = 0, Invalid = 0,
// Frequency // Frequency
FrequencyBase = 1, FrequencyBase = 1,
FrequencyBits = 2, FrequencyBits = 2,
FrequencyMask = ( ( 1 << FrequencyBits ) - 1 ) << FrequencyBase, FrequencyMask = ( ( 1 << FrequencyBits ) - 1 ) << FrequencyBase,
Detail = 0b01 << FrequencyBase, Detail = 0b01 << FrequencyBase,
Normal = 0b10 << FrequencyBase, Normal = 0b10 << FrequencyBase,
Overview = 0b11 << FrequencyBase, Overview = 0b11 << FrequencyBase,
// Type // Type
TypeBase = FrequencyBase + FrequencyBits, TypeBase = FrequencyBase + FrequencyBits,
TypeBits = 3, TypeBits = 3,
TypeMask = ( ( 1 << TypeBits ) - 1 ) << TypeBase, TypeMask = ( ( 1 << TypeBits ) - 1 ) << TypeBase,
Startup = 0b001 << TypeBase, Startup = 0b001 << TypeBase,
Running = 0b010 << TypeBase, Running = 0b010 << TypeBase,
Shutdown= 0b011 << TypeBase, Shutdown = 0b011 << TypeBase,
Error = 0b101 << TypeBase, Error = 0b101 << TypeBase,
} }
@ -42,22 +42,22 @@ namespace lib
[Flags] [Flags]
public enum LogType public enum LogType
{ {
Invalid = 0, Invalid = 0,
Trace = 1, Trace = 1,
Debug = 2, Debug = 2,
Info = 3, Info = 3,
Warn = 4, Warn = 4,
Error = 5, Error = 5,
Fatal = 6, Fatal = 6,
} }
public struct LogEvent public struct LogEvent
{ {
public DateTime Time; public DateTime Time;
public LogType LogType; public LogType LogType;
public string Cat; public string Cat;
public string Msg; public string Msg;
public object Obj; public object Obj;
public LogEvent( LogType logType, string cat, string msg, object obj ) public LogEvent( LogType logType, string cat, string msg, object obj )
{ {
@ -107,12 +107,12 @@ namespace lib
// Forwards. // Forwards.
static public void fatal( string msg, string cat = "unk", object obj = null ) 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 ) 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 )
@ -122,17 +122,17 @@ namespace lib
static public void info( string msg, string cat = "unk", object obj = null ) 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 ) 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 ) 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 ) 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() ); 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. //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 ) ) if( !value.Equals( notExpectedValue ) )
@ -278,7 +278,8 @@ namespace lib
return '*'; return '*';
case LogType.Fatal: case LogType.Fatal:
return '*'; return '*';
default: return '?'; default:
return '?';
} }
} }

74
Pos.cs
View File

@ -3,50 +3,50 @@ using System;
namespace lib namespace lib
{ {
[Serializable] [Serializable]
public struct Pos 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; public float x { get; private set; }
y = _y; public float y { get; private set; }
z = _z; public float z { get; private set; }
}
// 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 ) public Pos( float _x, float _y, float _z ) : this()
{ {
return new Pos( a.x - b.x, a.y - b.y, a.z - b.z ); x = _x;
} y = _y;
z = _z;
}
public static Pos operator /( Pos a, float val ) // overload operator +
{ public static Pos operator +( Pos a, Pos b )
return new Pos( a.x / val, a.y / val, a.z / val ); {
} return new Pos( a.x + b.x, a.y + b.y, a.z + b.z );
}
public static Pos operator *( Pos a, float val ) public static Pos operator -( Pos a, Pos b )
{ {
return new Pos( a.x * val, a.y * val, a.z * val ); return new Pos( a.x - b.x, a.y - b.y, a.z - b.z );
} }
public float distSqr( Pos other ) public static Pos operator /( Pos a, float val )
{ {
float dx = x - other.x; return new Pos( a.x / val, a.y / val, a.z / val );
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;
}
} }
}
} }

12
Scr.cs
View File

@ -48,9 +48,10 @@ static public class scr
{ {
var success = m_en.MoveNext(); 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() ) )
{ {
} }
@ -99,8 +100,8 @@ static public class scr
} }
#endregion #endregion
IEnumerator<T> m_en; IEnumerator<T> m_en;
Predicate<T> m_pred; Predicate<T> m_pred;
} }
@ -181,7 +182,8 @@ static public class scr
public static ImmutableList<PropertyInfo> GetAllProperties( Type t ) 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>(); var list = new List<PropertyInfo>();

View File

@ -10,148 +10,156 @@ using System.Security.Permissions;
namespace lib namespace lib
{ {
[Serializable] [Serializable]
public class SerializableDictionary<TKey, TVal> : Dictionary<TKey, TVal>, IXmlSerializable, ISerializable public class SerializableDictionary<TKey, TVal> : Dictionary<TKey, TVal>, IXmlSerializable, ISerializable
{ {
#region Constants #region Constants
private const string DictionaryNodeName = "Dictionary"; private const string DictionaryNodeName = "Dictionary";
private const string ItemNodeName = "Item"; private const string ItemNodeName = "Item";
private const string KeyNodeName = "Key"; private const string KeyNodeName = "Key";
private const string ValueNodeName = "Value"; private const string ValueNodeName = "Value";
#endregion #endregion
#region Constructors #region Constructors
public SerializableDictionary() public SerializableDictionary()
{ {
} }
public SerializableDictionary(IDictionary<TKey,TVal> dictionary) public SerializableDictionary( IDictionary<TKey, TVal> dictionary )
: base(dictionary) : base( dictionary )
{ {
} }
public SerializableDictionary(IEqualityComparer<TKey> comparer) public SerializableDictionary( IEqualityComparer<TKey> comparer )
: base(comparer) : base( comparer )
{ {
} }
public SerializableDictionary(int capacity) public SerializableDictionary( int capacity )
: base(capacity) : base( capacity )
{ {
} }
public SerializableDictionary(IDictionary<TKey,TVal> dictionary, IEqualityComparer<TKey> comparer) public SerializableDictionary( IDictionary<TKey, TVal> dictionary, IEqualityComparer<TKey> comparer )
: base(dictionary, comparer) : base( dictionary, comparer )
{ {
} }
public SerializableDictionary(int capacity, IEqualityComparer<TKey> comparer) public SerializableDictionary( int capacity, IEqualityComparer<TKey> comparer )
: base(capacity, comparer) : base( capacity, comparer )
{ {
} }
#endregion #endregion
#region ISerializable Members #region ISerializable Members
protected SerializableDictionary(SerializationInfo info, StreamingContext context) protected SerializableDictionary( SerializationInfo info, StreamingContext context )
{ {
int itemCount = info.GetInt32("ItemCount"); int itemCount = info.GetInt32("ItemCount");
for (int i = 0; i < itemCount; i++) { 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); 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)] [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context )
{ {
info.AddValue("ItemCount", this.Count); info.AddValue( "ItemCount", this.Count );
int itemIdx = 0; int itemIdx = 0;
foreach (KeyValuePair<TKey, TVal> kvp in this) { foreach( KeyValuePair<TKey, TVal> kvp in this )
info.AddValue(String.Format( $"Item{itemIdx}" ), kvp, typeof(KeyValuePair<TKey, TVal>)); {
itemIdx++; info.AddValue( String.Format( $"Item{itemIdx}" ), kvp, typeof( KeyValuePair<TKey, TVal> ) );
} itemIdx++;
} }
}
#endregion #endregion
#region IXmlSerializable Members #region IXmlSerializable Members
void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) void IXmlSerializable.WriteXml( System.Xml.XmlWriter writer )
{ {
//writer.WriteStartElement(DictionaryNodeName); //writer.WriteStartElement(DictionaryNodeName);
foreach (KeyValuePair<TKey, TVal> kvp in this) { foreach( KeyValuePair<TKey, TVal> kvp in this )
writer.WriteStartElement(ItemNodeName); {
writer.WriteStartElement(KeyNodeName); writer.WriteStartElement( ItemNodeName );
KeySerializer.Serialize(writer, kvp.Key); writer.WriteStartElement( KeyNodeName );
writer.WriteEndElement(); KeySerializer.Serialize( writer, kvp.Key );
writer.WriteStartElement(ValueNodeName); writer.WriteEndElement();
ValueSerializer.Serialize(writer, kvp.Value); writer.WriteStartElement( ValueNodeName );
writer.WriteEndElement(); ValueSerializer.Serialize( writer, kvp.Value );
writer.WriteEndElement(); writer.WriteEndElement();
} writer.WriteEndElement();
//writer.WriteEndElement(); }
} //writer.WriteEndElement();
}
void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) void IXmlSerializable.ReadXml( System.Xml.XmlReader reader )
{ {
if (reader.IsEmptyElement) { if( reader.IsEmptyElement )
return; {
} return;
}
// Move past container // Move past container
if (!reader.Read()){ if( !reader.Read() )
throw new XmlException("Error in Deserialization of Dictionary"); {
} throw new XmlException( "Error in Deserialization of Dictionary" );
}
//reader.ReadStartElement(DictionaryNodeName); //reader.ReadStartElement(DictionaryNodeName);
while (reader.NodeType != XmlNodeType.EndElement) { while( reader.NodeType != XmlNodeType.EndElement )
reader.ReadStartElement(ItemNodeName); {
reader.ReadStartElement(KeyNodeName); reader.ReadStartElement( ItemNodeName );
TKey key = (TKey)KeySerializer.Deserialize(reader); reader.ReadStartElement( KeyNodeName );
reader.ReadEndElement(); TKey key = (TKey)KeySerializer.Deserialize(reader);
reader.ReadStartElement(ValueNodeName); reader.ReadEndElement();
TVal value = (TVal)ValueSerializer.Deserialize(reader); reader.ReadStartElement( ValueNodeName );
reader.ReadEndElement(); TVal value = (TVal)ValueSerializer.Deserialize(reader);
reader.ReadEndElement(); reader.ReadEndElement();
this.Add(key, value); reader.ReadEndElement();
reader.MoveToContent(); this.Add( key, value );
} reader.MoveToContent();
//reader.ReadEndElement(); }
//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() System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{ {
return null; return null;
} }
#endregion #endregion
#region Private Properties #region Private Properties
protected XmlSerializer ValueSerializer protected XmlSerializer ValueSerializer
{ {
get get
{ {
if (valueSerializer == null) { if( valueSerializer == null )
valueSerializer = new XmlSerializer(typeof(TVal)); {
} valueSerializer = new XmlSerializer( typeof( TVal ) );
return valueSerializer; }
} return valueSerializer;
} }
}
private XmlSerializer KeySerializer private XmlSerializer KeySerializer
{ {
get get
{ {
if (keySerializer == null) { if( keySerializer == null )
keySerializer = new XmlSerializer(typeof(TKey)); {
} keySerializer = new XmlSerializer( typeof( TKey ) );
return keySerializer; }
} return keySerializer;
} }
#endregion }
#region Private Members #endregion
private XmlSerializer keySerializer = null; #region Private Members
private XmlSerializer valueSerializer = null; private XmlSerializer keySerializer = null;
#endregion private XmlSerializer valueSerializer = null;
} #endregion
}
} }

618
Timer.cs
View File

@ -6,336 +6,336 @@ using System.Threading;
namespace lib namespace lib
{ {
public class MicroStopwatch : System.Diagnostics.Stopwatch public class MicroStopwatch : System.Diagnostics.Stopwatch
{ {
readonly double _microSecPerTick readonly double _microSecPerTick
= 1000000D / System.Diagnostics.Stopwatch.Frequency; = 1000000D / System.Diagnostics.Stopwatch.Frequency;
public MicroStopwatch() 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
{ {
MicroStopwatch m_watch; if( !System.Diagnostics.Stopwatch.IsHighResolution )
private long startTime;
private long stopTime;
private long freq;
private long freq_millis;
public Timer()
{ {
m_watch = new MicroStopwatch(); throw new Exception( "On this system the high-resolution " +
//startTime = m_watch.ElapsedMicroseconds; "performance counter is not available" );
//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 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 public class TimerWin
{ {
[DllImport("Kernel32.dll")] [DllImport( "Kernel32.dll" )]
private static extern bool QueryPerformanceCounter( private static extern bool QueryPerformanceCounter(
out long lpPerformanceCount); out long lpPerformanceCount );
[DllImport("Kernel32.dll")] [DllImport( "Kernel32.dll" )]
private static extern bool QueryPerformanceFrequency( private static extern bool QueryPerformanceFrequency(
out long lpFrequency); out long lpFrequency );
private long startTime; private long startTime;
private long stopTime; private long stopTime;
private long freq; private long freq;
private long freq_millis; private long freq_millis;
// Constructor // Constructor
public TimerWin() public TimerWin()
{ {
startTime = 0; startTime = 0;
stopTime = 0; stopTime = 0;
if (QueryPerformanceFrequency(out freq) == false) if( QueryPerformanceFrequency( out freq ) == false )
{ {
// high-performance counter not supported // high-performance counter not supported
throw new Win32Exception(); throw new Win32Exception();
} }
freq_millis = freq / 1000; freq_millis = freq / 1000;
} }
// Start the timer // Start the timer
public void Start() public void Start()
{ {
// lets do the waiting threads there work // 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() public void Stop()
{ {
QueryPerformanceCounter(out stopTime); QueryPerformanceCounter( out stopTime );
} }
public double Seconds public double Seconds
{ {
@ -371,7 +371,7 @@ namespace lib
public long DurationMS 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 namespace lib
{ {
//TODO PERF fix this and make it fast. //TODO PERF fix this and make it fast.
[Serializable] [Serializable]
public struct Token public struct Token
{
public string str { get{ return m_str; } }
public Token( String str )
{ {
m_str = str; public string str { get { return m_str; } }
m_hash = m_str.GetHashCode();
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 namespace lib
{ {
/// <summary> /// <summary>
/// Utility class. /// Utility class.
/// </summary> /// </summary>
internal sealed class Interop internal sealed class Interop
{ {
public static T Pin<T>(ref T source) where T : struct public static T Pin<T>( ref T source ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static T IncrementPinned<T>(T source) where T : struct public static T IncrementPinned<T>( T source ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static T AddPinned<T>(T source, int offset) where T : struct public static T AddPinned<T>( T source, int offset ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static void Pin<T>(T data) where T : class public static void Pin<T>( T data ) where T : class
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void* Fixed<T>(ref T data) public static unsafe void* Fixed<T>( ref T data )
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void* FixedOut<T>(out T data) public static unsafe void* FixedOut<T>( out T data )
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void* Fixed<T>(T[] data) public static unsafe void* Fixed<T>( T[] data )
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void* Cast<T>(ref T data) where T : struct public static unsafe void* Cast<T>( ref T data ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void* CastOut<T>(out T data) where T : struct public static unsafe void* CastOut<T>( out T data ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static TCAST[] CastArray<TCAST, T>(T[] arrayData) public static TCAST[] CastArray<TCAST, T>( T[] arrayData )
where T : struct where T : struct
where TCAST : struct where TCAST : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl( MethodImplOptions.AggressiveInlining )]
public static unsafe void memcpy(void* pDest, void* pSrc, int count) public static unsafe void memcpy( void* pDest, void* pSrc, int count )
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl( MethodImplOptions.AggressiveInlining )]
public static unsafe void memset(void* pDest, byte value, int count) public static unsafe void memset( void* pDest, byte value, int count )
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void* Read<T>(void* pSrc, ref T data) where T : struct public static unsafe void* Read<T>( void* pSrc, ref T data ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe T ReadInline<T>(void* pSrc) where T : struct public static unsafe T ReadInline<T>( void* pSrc ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void WriteInline<T>(void* pDest, ref T data) where T : struct public static unsafe void WriteInline<T>( void* pDest, ref T data ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void CopyInline<T>(ref T data, void* pSrc) where T : struct public static unsafe void CopyInline<T>( ref T data, void* pSrc ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void CopyInline<T>(void* pDest, ref T srcData) public static unsafe void CopyInline<T>( void* pDest, ref T srcData )
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void CopyInlineOut<T>(out T data, void* pSrc) public static unsafe void CopyInlineOut<T>( out T data, void* pSrc )
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void* ReadOut<T>(void* pSrc, out T data) where T : struct public static unsafe void* ReadOut<T>( void* pSrc, out T data ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void* Read<T>(void* pSrc, T[] data, int offset, int count) where T : struct public static unsafe void* Read<T>( void* pSrc, T[] data, int offset, int count ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void* Read2D<T>(void* pSrc, T[,] data, int offset, int count) where T : struct public static unsafe void* Read2D<T>( void* pSrc, T[,] data, int offset, int count ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl( MethodImplOptions.AggressiveInlining )]
public static int SizeOf<T>() public static int SizeOf<T>()
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void* Write<T>(void* pDest, ref T data) where T : struct public static unsafe void* Write<T>( void* pDest, ref T data ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void* Write<T>(void* pDest, T[] data, int offset, int count) where T : struct public static unsafe void* Write<T>( void* pDest, T[] data, int offset, int count ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static unsafe void* Write2D<T>(void* pDest, T[,] data, int offset, int count) where T : struct public static unsafe void* Write2D<T>( void* pDest, T[,] data, int offset, int count ) where T : struct
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -116,9 +116,9 @@ namespace lib
int objRef = obj.GetHashCode(); int objRef = obj.GetHashCode();
writer.Write( objRef ); 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 ); m_objectsToBeDeserialized.Enqueue( obj );
} }
} }
@ -160,43 +160,43 @@ namespace lib
switch( typeName ) switch( typeName )
{ {
case "Int32": case "Int32":
writer.Write( (char)ETypes.Int32 ); writer.Write( (char)ETypes.Int32 );
writer.Write( name.GetHashCode() ); writer.Write( name.GetHashCode() );
write( writer, Convert.ToInt32( fi.GetValue( parentObj ) ) ); write( writer, Convert.ToInt32( fi.GetValue( parentObj ) ) );
break; break;
case "Single": case "Single":
writer.Write( (char)ETypes.Single ); writer.Write( (char)ETypes.Single );
writer.Write( name.GetHashCode() ); writer.Write( name.GetHashCode() );
write( writer, Convert.ToSingle( fi.GetValue( parentObj ) ) ); write( writer, Convert.ToSingle( fi.GetValue( parentObj ) ) );
break; break;
case "Double": case "Double":
writer.Write( (char)ETypes.Double ); writer.Write( (char)ETypes.Double );
writer.Write( name.GetHashCode() ); writer.Write( name.GetHashCode() );
write( writer, Convert.ToDouble( fi.GetValue( parentObj ) ) ); write( writer, Convert.ToDouble( fi.GetValue( parentObj ) ) );
break; break;
case "Char": case "Char":
writer.Write( (char)ETypes.Char ); writer.Write( (char)ETypes.Char );
writer.Write( name.GetHashCode() ); writer.Write( name.GetHashCode() );
write( writer, Convert.ToChar( fi.GetValue( parentObj ) ) ); write( writer, Convert.ToChar( fi.GetValue( parentObj ) ) );
break; break;
case "String": case "String":
writer.Write( (char)ETypes.String ); writer.Write( (char)ETypes.String );
writer.Write( name.GetHashCode() ); writer.Write( name.GetHashCode() );
write( writer, Convert.ToString( fi.GetValue( parentObj ) ) ); write( writer, Convert.ToString( fi.GetValue( parentObj ) ) );
break; break;
case "Boolean": case "Boolean":
writer.Write( (char)ETypes.Boolean ); writer.Write( (char)ETypes.Boolean );
writer.Write( name.GetHashCode() ); writer.Write( name.GetHashCode() );
writer.Write( Convert.ToBoolean( fi.GetValue( parentObj ) ) ); writer.Write( Convert.ToBoolean( fi.GetValue( parentObj ) ) );
break; break;
default: default:
Console.WriteLine( "VersionFormatter does not understand type " + typeName ); Console.WriteLine( "VersionFormatter does not understand type " + typeName );
break; break;
} }
} }
@ -299,16 +299,16 @@ namespace lib
{ {
public Fixup( int guid, object obj, FieldInfo fi ) public Fixup( int guid, object obj, FieldInfo fi )
{ {
m_guid= guid; m_guid = guid;
m_obj = obj; m_obj = obj;
m_fi = fi; m_fi = fi;
} }
public Fixup( int guid, object obj, int index ) public Fixup( int guid, object obj, int index )
{ {
m_guid = guid; m_guid = guid;
m_obj = obj; m_obj = obj;
m_index= index; m_index = index;
} }
public readonly int m_guid = 0; public readonly int m_guid = 0;
@ -381,7 +381,7 @@ namespace lib
object []array = (object [])fu.m_obj; object []array = (object [])fu.m_obj;
array[ fu.m_index ] = obj; array[fu.m_index] = obj;
} }
} }
else else
@ -433,34 +433,34 @@ namespace lib
switch( type ) switch( type )
{ {
case ETypes.Array: case ETypes.Array:
readArray( reader, obj, fi ); readArray( reader, obj, fi );
break; break;
case ETypes.Int32: case ETypes.Int32:
readInt( reader, obj, fi ); readInt( reader, obj, fi );
break; break;
case ETypes.Single: case ETypes.Single:
readSingle( reader, obj, fi ); readSingle( reader, obj, fi );
break; break;
case ETypes.Double: case ETypes.Double:
readDouble( reader, obj, fi ); readDouble( reader, obj, fi );
break; break;
case ETypes.Char: case ETypes.Char:
readChar( reader, obj, fi ); readChar( reader, obj, fi );
break; break;
case ETypes.Boolean: case ETypes.Boolean:
readBool( reader, obj, fi ); readBool( reader, obj, fi );
break; break;
case ETypes.String: case ETypes.String:
readString( reader, obj, fi ); readString( reader, obj, fi );
break; break;
case ETypes.Ref: case ETypes.Ref:
readRef( reader, obj, fi ); readRef( reader, obj, fi );
break; break;
case ETypes.Object: case ETypes.Object:
readObject( reader ); readObject( reader );
break; break;
default: default:
Debug.Fail( "Unknown type on read." ); Debug.Fail( "Unknown type on read." );
break; break;
} }
} }
@ -510,7 +510,7 @@ namespace lib
{ {
object obj = createObject( objTypeName ); object obj = createObject( objTypeName );
m_mapGUIDToObject[ objGUID ] = obj; m_mapGUIDToObject[objGUID] = obj;
ArrayList list = new ArrayList(); ArrayList list = new ArrayList();
Hashtable ht = new Hashtable(); Hashtable ht = new Hashtable();
@ -521,7 +521,7 @@ namespace lib
foreach( FieldInfo fi in list ) foreach( FieldInfo fi in list )
{ {
ht[ fi.Name.GetHashCode() ] = fi; ht[fi.Name.GetHashCode()] = fi;
} }
} }
@ -545,7 +545,8 @@ namespace lib
if( length < 0 ) if( length < 0 )
{ {
if( fi == null ) return; if( fi == null )
return;
fi.SetValue( obj, null ); fi.SetValue( obj, null );
@ -559,7 +560,7 @@ namespace lib
fi.SetValue( obj, array ); fi.SetValue( obj, array );
} }
for( int i=0; i<length; ++i ) for( int i = 0; i < length; ++i )
{ {
int val = reader.ReadInt32(); int val = reader.ReadInt32();
@ -585,7 +586,8 @@ namespace lib
{ {
int val = reader.ReadInt32(); int val = reader.ReadInt32();
if( fi == null ) return; if( fi == null )
return;
if( !fi.FieldType.IsEnum ) if( !fi.FieldType.IsEnum )
{ {
@ -603,7 +605,8 @@ namespace lib
{ {
float val = reader.ReadSingle(); float val = reader.ReadSingle();
if( fi == null ) return; if( fi == null )
return;
fi.SetValue( obj, val ); fi.SetValue( obj, val );
} }
@ -612,7 +615,8 @@ namespace lib
{ {
double val = reader.ReadDouble(); double val = reader.ReadDouble();
if( fi == null ) return; if( fi == null )
return;
fi.SetValue( obj, val ); fi.SetValue( obj, val );
} }
@ -621,7 +625,8 @@ namespace lib
{ {
char val = reader.ReadChar(); char val = reader.ReadChar();
if( fi == null ) return; if( fi == null )
return;
fi.SetValue( obj, val ); fi.SetValue( obj, val );
} }
@ -630,7 +635,8 @@ namespace lib
{ {
string val = reader.ReadString(); string val = reader.ReadString();
if( fi == null ) return; if( fi == null )
return;
fi.SetValue( obj, val ); fi.SetValue( obj, val );
} }
@ -639,7 +645,8 @@ namespace lib
{ {
bool val = reader.ReadBoolean(); bool val = reader.ReadBoolean();
if( fi == null ) return; if( fi == null )
return;
fi.SetValue( obj, val ); fi.SetValue( obj, val );
} }

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

View File

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

View File

@ -9,79 +9,79 @@ using System.Reflection;
namespace mod namespace mod
{ {
[Serializable] [Serializable]
public class Config : lib.Config 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 )
{ {
m_cfg = cfg; public String name = "Generic";
} }
private Config m_cfg; public class View
}
[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 Base
[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; 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

@ -156,7 +156,7 @@ namespace res
var lh = new LoadHolder<T>( loader ); 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 //Register all subclasses of a particular type
@ -244,7 +244,8 @@ namespace res
{ {
if( ResCache<T>.s_cache.TryGetValue( filename, out var wr ) ) 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." ); 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( 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>; var loader = loaderGen as LoadHolder<T>;
@ -302,7 +303,7 @@ namespace res
} }
else 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; return ResCache<T>.s_default;
} }