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,14 +14,14 @@ 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;
@ -35,7 +35,7 @@ namespace lib
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;

View File

@ -6,27 +6,27 @@ using System.Reflection;
namespace lib namespace lib
{ {
public class DescAttribute : Attribute public class DescAttribute : Attribute
{ {
public string Desc { get; private set; } public string Desc { get; private set; }
public DescAttribute( string desc ) public DescAttribute( string desc )
{ {
Desc = desc; Desc = desc;
} }
} }
[Serializable] [Serializable]
public class ConfigCfg : Config public class ConfigCfg : Config
{ {
public readonly bool writeOutTemplateFiles = true; public readonly bool writeOutTemplateFiles = true;
} }
[Serializable] [Serializable]
public class Config public class Config
{ {
/* /*
static public Config Load( string filename ) static public Config Load( string filename )
{ {
@ -39,7 +39,7 @@ public class Config
static public void startup( string filename ) static public void startup( string filename )
{ {
res.Mgr.register<Config>( load ); res.Mgr.register<Config>( load );
res.Mgr.registerSub(typeof(Config)); res.Mgr.registerSub( typeof( Config ) );
s_cfg = Config.load<ConfigCfg>( filename ); s_cfg = Config.load<ConfigCfg>( filename );
@ -93,7 +93,7 @@ public class Config
XmlFormatter2 formatter = new XmlFormatter2(); XmlFormatter2 formatter = new XmlFormatter2();
cfg = (Config)( t != null ? formatter.DeserializeKnownType( fs,t ) : formatter.Deserialize( fs ) ); cfg = (Config)( t != null ? formatter.DeserializeKnownType( fs, t ) : formatter.Deserialize( fs ) );
cfg.SetFilename( filename ); cfg.SetFilename( filename );
} }
@ -167,6 +167,6 @@ public class Config
protected void SetFilename( String filename ) { m_filename = filename; } protected void SetFilename( String filename ) { m_filename = filename; }
} }
} }

15
Conn.cs
View File

@ -12,16 +12,16 @@ namespace lib
public interface IProcess public interface IProcess
{ {
void process( object obj ); void process( object obj );
} }
public class Conn public class Conn
{ {
public Socket Sock { get { return m_socket; } } public Socket Sock { get { return m_socket; } }
public Stream Stream { get { return m_streamNet; } } public Stream Stream { get { return m_streamNet; } }
@ -89,7 +89,8 @@ public class Conn
public virtual void recieve( object obj ) public virtual void recieve( object obj )
{ {
if( m_proc != null ) m_proc.process( obj ); if( m_proc != null )
m_proc.process( obj );
} }
Socket m_socket; Socket m_socket;
@ -102,7 +103,7 @@ public class Conn
//private BufferedStream m_streamBufIn; //private BufferedStream m_streamBufIn;
//private BufferedStream m_streamBufOut; //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
{ {

17
Log.cs
View File

@ -33,7 +33,7 @@ namespace lib
Startup = 0b001 << TypeBase, Startup = 0b001 << TypeBase,
Running = 0b010 << TypeBase, Running = 0b010 << TypeBase,
Shutdown= 0b011 << TypeBase, Shutdown = 0b011 << TypeBase,
Error = 0b101 << TypeBase, Error = 0b101 << TypeBase,
} }
@ -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 )
@ -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 '?';
} }
} }

8
Pos.cs
View File

@ -3,9 +3,9 @@ using System;
namespace lib namespace lib
{ {
[Serializable] [Serializable]
public struct Pos public struct Pos
{ {
public float x { get; private set; } public float x { get; private set; }
public float y { get; private set; } public float y { get; private set; }
public float z { get; private set; } public float z { get; private set; }
@ -47,6 +47,6 @@ public struct Pos
return dx * dx + dy * dy + dz * dz; return dx * dx + dy * dy + dz * dz;
} }
} }
} }

8
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() ) )
{ {
} }
@ -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

@ -24,50 +24,52 @@ namespace lib
{ {
} }
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>)); KeyValuePair<TKey, TVal> kvp = (KeyValuePair<TKey, TVal>)info.GetValue(String.Format( $"Item{i}" ), typeof(KeyValuePair<TKey, TVal>));
this.Add(kvp.Key, kvp.Value); 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>)); {
info.AddValue( String.Format( $"Item{itemIdx}" ), kvp, typeof( KeyValuePair<TKey, TVal> ) );
itemIdx++; itemIdx++;
} }
} }
@ -75,44 +77,48 @@ namespace lib
#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 );
KeySerializer.Serialize( writer, kvp.Key );
writer.WriteEndElement(); writer.WriteEndElement();
writer.WriteStartElement(ValueNodeName); writer.WriteStartElement( ValueNodeName );
ValueSerializer.Serialize(writer, kvp.Value); ValueSerializer.Serialize( writer, kvp.Value );
writer.WriteEndElement(); 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 );
reader.ReadStartElement( KeyNodeName );
TKey key = (TKey)KeySerializer.Deserialize(reader); TKey key = (TKey)KeySerializer.Deserialize(reader);
reader.ReadEndElement(); reader.ReadEndElement();
reader.ReadStartElement(ValueNodeName); reader.ReadStartElement( ValueNodeName );
TVal value = (TVal)ValueSerializer.Deserialize(reader); TVal value = (TVal)ValueSerializer.Deserialize(reader);
reader.ReadEndElement(); reader.ReadEndElement();
reader.ReadEndElement(); reader.ReadEndElement();
this.Add(key, value); this.Add( key, value );
reader.MoveToContent(); reader.MoveToContent();
} }
//reader.ReadEndElement(); //reader.ReadEndElement();
@ -131,8 +137,9 @@ namespace lib
{ {
get get
{ {
if (valueSerializer == null) { if( valueSerializer == null )
valueSerializer = new XmlSerializer(typeof(TVal)); {
valueSerializer = new XmlSerializer( typeof( TVal ) );
} }
return valueSerializer; return valueSerializer;
} }
@ -142,8 +149,9 @@ namespace lib
{ {
get get
{ {
if (keySerializer == null) { if( keySerializer == null )
keySerializer = new XmlSerializer(typeof(TKey)); {
keySerializer = new XmlSerializer( typeof( TKey ) );
} }
return keySerializer; return keySerializer;
} }

View File

@ -13,10 +13,10 @@ namespace lib
public MicroStopwatch() public MicroStopwatch()
{ {
if (!System.Diagnostics.Stopwatch.IsHighResolution) if( !System.Diagnostics.Stopwatch.IsHighResolution )
{ {
throw new Exception("On this system the high-resolution " + throw new Exception( "On this system the high-resolution " +
"performance counter is not available"); "performance counter is not available" );
} }
} }
@ -24,7 +24,7 @@ namespace lib
{ {
get get
{ {
return (long)(ElapsedTicks * _microSecPerTick); return (long)( ElapsedTicks * _microSecPerTick );
} }
} }
} }
@ -36,7 +36,7 @@ namespace lib
{ {
public delegate void MicroTimerElapsedEventHandler( public delegate void MicroTimerElapsedEventHandler(
object sender, object sender,
MicroTimerEventArgs timerEventArgs); MicroTimerEventArgs timerEventArgs );
public event MicroTimerElapsedEventHandler MicroTimerElapsed; public event MicroTimerElapsedEventHandler MicroTimerElapsed;
System.Threading.Thread _threadTimer = null; System.Threading.Thread _threadTimer = null;
@ -48,7 +48,7 @@ namespace lib
{ {
} }
public MicroTimer(long timerIntervalInMicroseconds) public MicroTimer( long timerIntervalInMicroseconds )
{ {
Interval = timerIntervalInMicroseconds; Interval = timerIntervalInMicroseconds;
} }
@ -58,12 +58,12 @@ namespace lib
get get
{ {
return System.Threading.Interlocked.Read( return System.Threading.Interlocked.Read(
ref _timerIntervalInMicroSec); ref _timerIntervalInMicroSec );
} }
set set
{ {
System.Threading.Interlocked.Exchange( System.Threading.Interlocked.Exchange(
ref _timerIntervalInMicroSec, value); ref _timerIntervalInMicroSec, value );
} }
} }
@ -72,12 +72,12 @@ namespace lib
get get
{ {
return System.Threading.Interlocked.Read( return System.Threading.Interlocked.Read(
ref _ignoreEventIfLateBy); ref _ignoreEventIfLateBy );
} }
set set
{ {
System.Threading.Interlocked.Exchange( System.Threading.Interlocked.Exchange(
ref _ignoreEventIfLateBy, value <= 0 ? long.MaxValue : value); ref _ignoreEventIfLateBy, value <= 0 ? long.MaxValue : value );
} }
} }
@ -85,7 +85,7 @@ namespace lib
{ {
set set
{ {
if (value) if( value )
{ {
Start(); Start();
} }
@ -96,13 +96,13 @@ namespace lib
} }
get get
{ {
return (_threadTimer != null && _threadTimer.IsAlive); return ( _threadTimer != null && _threadTimer.IsAlive );
} }
} }
public void Start() public void Start()
{ {
if (Enabled || Interval <= 0) if( Enabled || Interval <= 0 )
{ {
return; return;
} }
@ -116,7 +116,7 @@ namespace lib
ref _stopTimer); ref _stopTimer);
}; };
_threadTimer = new System.Threading.Thread(threadStart); _threadTimer = new System.Threading.Thread( threadStart );
_threadTimer.Priority = System.Threading.ThreadPriority.Highest; _threadTimer.Priority = System.Threading.ThreadPriority.Highest;
_threadTimer.Start(); _threadTimer.Start();
} }
@ -125,21 +125,21 @@ namespace lib
{ {
_stopTimer = true; _stopTimer = true;
if (_threadTimer != null && _threadTimer.ManagedThreadId == if( _threadTimer != null && _threadTimer.ManagedThreadId ==
System.Threading.Thread.CurrentThread.ManagedThreadId) System.Threading.Thread.CurrentThread.ManagedThreadId )
{ {
return; return;
} }
while (Enabled) while( Enabled )
{ {
System.Threading.Thread.SpinWait(10); System.Threading.Thread.SpinWait( 10 );
} }
} }
void NotificationTimer(ref long timerIntervalInMicroSec, void NotificationTimer( ref long timerIntervalInMicroSec,
ref long ignoreEventIfLateBy, ref long ignoreEventIfLateBy,
ref bool stopTimer) ref bool stopTimer )
{ {
int timerCount = 0; int timerCount = 0;
long nextNotification = 0; long nextNotification = 0;
@ -147,7 +147,7 @@ namespace lib
MicroStopwatch microStopwatch = new MicroStopwatch(); MicroStopwatch microStopwatch = new MicroStopwatch();
microStopwatch.Start(); microStopwatch.Start();
while (!stopTimer) while( !stopTimer )
{ {
long callbackFunctionExecutionTime = long callbackFunctionExecutionTime =
microStopwatch.ElapsedMicroseconds - nextNotification; microStopwatch.ElapsedMicroseconds - nextNotification;
@ -161,15 +161,15 @@ namespace lib
timerCount++; timerCount++;
long elapsedMicroseconds = 0; long elapsedMicroseconds = 0;
while ( (elapsedMicroseconds = microStopwatch.ElapsedMicroseconds) while( ( elapsedMicroseconds = microStopwatch.ElapsedMicroseconds )
< nextNotification) < nextNotification )
{ {
System.Threading.Thread.SpinWait(10); System.Threading.Thread.SpinWait( 10 );
} }
long timerLateBy = elapsedMicroseconds - nextNotification; long timerLateBy = elapsedMicroseconds - nextNotification;
if (timerLateBy >= ignoreEventIfLateByCurrent) if( timerLateBy >= ignoreEventIfLateByCurrent )
{ {
continue; continue;
} }
@ -179,7 +179,7 @@ namespace lib
elapsedMicroseconds, elapsedMicroseconds,
timerLateBy, timerLateBy,
callbackFunctionExecutionTime); callbackFunctionExecutionTime);
MicroTimerElapsed(this, microTimerEventArgs); MicroTimerElapsed( this, microTimerEventArgs );
} }
microStopwatch.Stop(); microStopwatch.Stop();
@ -203,10 +203,10 @@ namespace lib
// Time it took to execute previous call to callback function (OnTimedEvent) // Time it took to execute previous call to callback function (OnTimedEvent)
public long CallbackFunctionExecutionTime { get; private set; } public long CallbackFunctionExecutionTime { get; private set; }
public MicroTimerEventArgs(int timerCount, public MicroTimerEventArgs( int timerCount,
long elapsedMicroseconds, long elapsedMicroseconds,
long timerLateBy, long timerLateBy,
long callbackFunctionExecutionTime) long callbackFunctionExecutionTime )
{ {
TimerCount = timerCount; TimerCount = timerCount;
ElapsedMicroseconds = elapsedMicroseconds; ElapsedMicroseconds = elapsedMicroseconds;
@ -289,13 +289,13 @@ namespace lib
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;
@ -309,7 +309,7 @@ namespace lib
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();
@ -327,14 +327,14 @@ namespace lib
//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,12 +4,12 @@ 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 string str { get { return m_str; } }
public Token( String str ) public Token( String str )
{ {
@ -49,6 +49,6 @@ public struct Token
int m_hash; int m_hash;
String m_str; String m_str;
} }
} }

View File

@ -32,132 +32,132 @@ namespace lib
/// </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();
} }

View File

@ -102,16 +102,16 @@ namespace lib
/// <param name="against">The pointer to compare against.</param> /// <param name="against">The pointer to compare against.</param>
/// <param name="sizeToCompare">The size in bytes to compare.</param> /// <param name="sizeToCompare">The size in bytes to compare.</param>
/// <returns>True if the buffers are equivalent, false otherwise.</returns> /// <returns>True if the buffers are equivalent, false otherwise.</returns>
public static unsafe bool CompareMemory(IntPtr from, IntPtr against, int sizeToCompare) public static unsafe bool CompareMemory( IntPtr from, IntPtr against, int sizeToCompare )
{ {
var pSrc = (byte*)from; var pSrc = (byte*)from;
var pDst = (byte*)against; var pDst = (byte*)against;
// Compare 8 bytes. // Compare 8 bytes.
var numberOf = sizeToCompare >> 3; var numberOf = sizeToCompare >> 3;
while (numberOf > 0) while( numberOf > 0 )
{ {
if (*(long*)pSrc != *(long*)pDst) if( *(long*)pSrc != *(long*)pDst )
return false; return false;
pSrc += 8; pSrc += 8;
pDst += 8; pDst += 8;
@ -120,9 +120,9 @@ namespace lib
// Compare remaining bytes. // Compare remaining bytes.
numberOf = sizeToCompare & 7; numberOf = sizeToCompare & 7;
while (numberOf > 0) while( numberOf > 0 )
{ {
if (*pSrc != *pDst) if( *pSrc != *pDst )
return false; return false;
pSrc++; pSrc++;
pDst++; pDst++;
@ -138,11 +138,11 @@ namespace lib
/// <param name="dest">The dest.</param> /// <param name="dest">The dest.</param>
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
/// <param name="sizeInBytesToClear">The size in bytes to clear.</param> /// <param name="sizeInBytesToClear">The size in bytes to clear.</param>
public static void ClearMemory(IntPtr dest, byte value, int sizeInBytesToClear) public static void ClearMemory( IntPtr dest, byte value, int sizeInBytesToClear )
{ {
unsafe unsafe
{ {
Interop.memset((void*)dest, value, sizeInBytesToClear); Interop.memset( (void*)dest, value, sizeInBytesToClear );
} }
} }
@ -162,7 +162,7 @@ namespace lib
/// <typeparam name="T">a struct</typeparam> /// <typeparam name="T">a struct</typeparam>
/// <param name="array">The array of struct to evaluate.</param> /// <param name="array">The array of struct to evaluate.</param>
/// <returns>sizeof in bytes of this array of struct</returns> /// <returns>sizeof in bytes of this array of struct</returns>
public static int SizeOf<T>(T[] array) where T : struct public static int SizeOf<T>( T[] array ) where T : struct
{ {
return array == null ? 0 : array.Length * Interop.SizeOf<T>(); return array == null ? 0 : array.Length * Interop.SizeOf<T>();
} }
@ -173,11 +173,11 @@ namespace lib
/// <typeparam name="T">The type of the structure to pin</typeparam> /// <typeparam name="T">The type of the structure to pin</typeparam>
/// <param name="source">The source.</param> /// <param name="source">The source.</param>
/// <param name="pinAction">The pin action to perform on the pinned pointer.</param> /// <param name="pinAction">The pin action to perform on the pinned pointer.</param>
public static void Pin<T>(ref T source, Action<IntPtr> pinAction) where T : struct public static void Pin<T>( ref T source, Action<IntPtr> pinAction ) where T : struct
{ {
unsafe unsafe
{ {
pinAction((IntPtr)Interop.Fixed(ref source)); pinAction( (IntPtr)Interop.Fixed( ref source ) );
} }
} }
@ -187,11 +187,11 @@ namespace lib
/// <typeparam name="T">The type of the structure to pin</typeparam> /// <typeparam name="T">The type of the structure to pin</typeparam>
/// <param name="source">The source array.</param> /// <param name="source">The source array.</param>
/// <param name="pinAction">The pin action to perform on the pinned pointer.</param> /// <param name="pinAction">The pin action to perform on the pinned pointer.</param>
public static void Pin<T>(T[] source, [NotNull] Action<IntPtr> pinAction) where T : struct public static void Pin<T>( T[] source, [NotNull] Action<IntPtr> pinAction ) where T : struct
{ {
unsafe unsafe
{ {
pinAction(source == null ? IntPtr.Zero : (IntPtr)Interop.Fixed(source)); pinAction( source == null ? IntPtr.Zero : (IntPtr)Interop.Fixed( source ) );
} }
} }
@ -200,19 +200,20 @@ namespace lib
/// </summary> /// </summary>
/// <param name="source">The source.</param> /// <param name="source">The source.</param>
/// <returns>The byte array.</returns> /// <returns>The byte array.</returns>
public static byte[] ToByteArray<T>(T[] source) where T : struct public static byte[] ToByteArray<T>( T[] source ) where T : struct
{ {
if (source == null) return null; if( source == null )
return null;
var buffer = new byte[SizeOf<T>() * source.Length]; var buffer = new byte[SizeOf<T>() * source.Length];
if (source.Length == 0) if( source.Length == 0 )
return buffer; return buffer;
unsafe unsafe
{ {
fixed (void* pBuffer = buffer) fixed ( void* pBuffer = buffer )
Interop.Write(pBuffer, source, 0, source.Length); Interop.Write( pBuffer, source, 0, source.Length );
} }
return buffer; return buffer;
} }
@ -223,11 +224,11 @@ namespace lib
/// <typeparam name="T">Type of a data to read</typeparam> /// <typeparam name="T">Type of a data to read</typeparam>
/// <param name="source">Memory location to read from.</param> /// <param name="source">Memory location to read from.</param>
/// <returns>The data read from the memory location</returns> /// <returns>The data read from the memory location</returns>
public static T Read<T>(IntPtr source) where T : struct public static T Read<T>( IntPtr source ) where T : struct
{ {
unsafe unsafe
{ {
return Interop.ReadInline<T>((void*)source); return Interop.ReadInline<T>( (void*)source );
} }
} }
@ -237,12 +238,12 @@ namespace lib
/// <typeparam name="T">Type of a data to read</typeparam> /// <typeparam name="T">Type of a data to read</typeparam>
/// <param name="source">Memory location to read from.</param> /// <param name="source">Memory location to read from.</param>
/// <param name="data">The data write to.</param> /// <param name="data">The data write to.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl( MethodImplOptions.AggressiveInlining )]
public static void Read<T>(IntPtr source, ref T data) where T : struct public static void Read<T>( IntPtr source, ref T data ) where T : struct
{ {
unsafe unsafe
{ {
Interop.CopyInline(ref data, (void*)source); Interop.CopyInline( ref data, (void*)source );
} }
} }
@ -252,11 +253,11 @@ namespace lib
/// <typeparam name="T">Type of a data to read</typeparam> /// <typeparam name="T">Type of a data to read</typeparam>
/// <param name="source">Memory location to read from.</param> /// <param name="source">Memory location to read from.</param>
/// <param name="data">The data write to.</param> /// <param name="data">The data write to.</param>
public static void ReadOut<T>(IntPtr source, out T data) where T : struct public static void ReadOut<T>( IntPtr source, out T data ) where T : struct
{ {
unsafe unsafe
{ {
Interop.CopyInlineOut(out data, (void*)source); Interop.CopyInlineOut( out data, (void*)source );
} }
} }
@ -267,11 +268,11 @@ namespace lib
/// <param name="source">Memory location to read from.</param> /// <param name="source">Memory location to read from.</param>
/// <param name="data">The data write to.</param> /// <param name="data">The data write to.</param>
/// <returns>source pointer + sizeof(T)</returns> /// <returns>source pointer + sizeof(T)</returns>
public static IntPtr ReadAndPosition<T>(IntPtr source, ref T data) where T : struct public static IntPtr ReadAndPosition<T>( IntPtr source, ref T data ) where T : struct
{ {
unsafe unsafe
{ {
return (IntPtr)Interop.Read((void*)source, ref data); return (IntPtr)Interop.Read( (void*)source, ref data );
} }
} }
@ -284,11 +285,11 @@ namespace lib
/// <param name="offset">The offset in the array to write to.</param> /// <param name="offset">The offset in the array to write to.</param>
/// <param name="count">The number of T element to read from the memory location</param> /// <param name="count">The number of T element to read from the memory location</param>
/// <returns>source pointer + sizeof(T) * count</returns> /// <returns>source pointer + sizeof(T) * count</returns>
public static IntPtr Read<T>(IntPtr source, T[] data, int offset, int count) where T : struct public static IntPtr Read<T>( IntPtr source, T[] data, int offset, int count ) where T : struct
{ {
unsafe unsafe
{ {
return (IntPtr)Interop.Read((void*)source, data, offset, count); return (IntPtr)Interop.Read( (void*)source, data, offset, count );
} }
} }
@ -298,12 +299,12 @@ namespace lib
/// <typeparam name="T">Type of a data to write</typeparam> /// <typeparam name="T">Type of a data to write</typeparam>
/// <param name="destination">Memory location to write to.</param> /// <param name="destination">Memory location to write to.</param>
/// <param name="data">The data to write.</param> /// <param name="data">The data to write.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl( MethodImplOptions.AggressiveInlining )]
public static void Write<T>(IntPtr destination, ref T data) where T : struct public static void Write<T>( IntPtr destination, ref T data ) where T : struct
{ {
unsafe unsafe
{ {
Interop.CopyInline((void*)destination, ref data); Interop.CopyInline( (void*)destination, ref data );
} }
} }
@ -314,11 +315,11 @@ namespace lib
/// <param name="destination">Memory location to write to.</param> /// <param name="destination">Memory location to write to.</param>
/// <param name="data">The data to write.</param> /// <param name="data">The data to write.</param>
/// <returns>destination pointer + sizeof(T)</returns> /// <returns>destination pointer + sizeof(T)</returns>
public static IntPtr WriteAndPosition<T>(IntPtr destination, ref T data) where T : struct public static IntPtr WriteAndPosition<T>( IntPtr destination, ref T data ) where T : struct
{ {
unsafe unsafe
{ {
return (IntPtr)Interop.Write((void*)destination, ref data); return (IntPtr)Interop.Write( (void*)destination, ref data );
} }
} }
@ -330,13 +331,13 @@ namespace lib
/// <param name="data">The array of T data to write.</param> /// <param name="data">The array of T data to write.</param>
/// <param name="offset">The offset in the array to read from.</param> /// <param name="offset">The offset in the array to read from.</param>
/// <param name="count">The number of T element to write to the memory location</param> /// <param name="count">The number of T element to write to the memory location</param>
public static void Write<T>(byte[] destination, T[] data, int offset, int count) where T : struct public static void Write<T>( byte[] destination, T[] data, int offset, int count ) where T : struct
{ {
unsafe unsafe
{ {
fixed (void* pDest = destination) fixed ( void* pDest = destination )
{ {
Write((IntPtr)pDest, data, offset, count); Write( (IntPtr)pDest, data, offset, count );
} }
} }
} }
@ -350,11 +351,11 @@ namespace lib
/// <param name="offset">The offset in the array to read from.</param> /// <param name="offset">The offset in the array to read from.</param>
/// <param name="count">The number of T element to write to the memory location</param> /// <param name="count">The number of T element to write to the memory location</param>
/// <returns>destination pointer + sizeof(T) * count</returns> /// <returns>destination pointer + sizeof(T) * count</returns>
public static IntPtr Write<T>(IntPtr destination, T[] data, int offset, int count) where T : struct public static IntPtr Write<T>( IntPtr destination, T[] data, int offset, int count ) where T : struct
{ {
unsafe unsafe
{ {
return (IntPtr)Interop.Write((void*)destination, data, offset, count); return (IntPtr)Interop.Write( (void*)destination, data, offset, count );
} }
} }
@ -367,17 +368,17 @@ namespace lib
/// <remarks> /// <remarks>
/// To free this buffer, call <see cref="FreeMemory"/> /// To free this buffer, call <see cref="FreeMemory"/>
/// </remarks> /// </remarks>
public static unsafe IntPtr AllocateMemory(int sizeInBytes, int align = 16) public static unsafe IntPtr AllocateMemory( int sizeInBytes, int align = 16 )
{ {
var mask = align - 1; var mask = align - 1;
if ((align & mask) != 0) if( ( align & mask ) != 0 )
{ {
throw new ArgumentException("Alignment is not power of 2", nameof(align)); throw new ArgumentException( "Alignment is not power of 2", nameof( align ) );
} }
var memPtr = Marshal.AllocHGlobal(sizeInBytes + mask + sizeof(void*)); var memPtr = Marshal.AllocHGlobal(sizeInBytes + mask + sizeof(void*));
var ptr = (byte*)((ulong)(memPtr.ToInt32() + sizeof(void*) + mask) & ~(ulong)mask); var ptr = (byte*)((ulong)(memPtr.ToInt32() + sizeof(void*) + mask) & ~(ulong)mask);
((IntPtr*)ptr)[-1] = memPtr; ( (IntPtr*)ptr )[-1] = memPtr;
return new IntPtr(ptr); return new IntPtr( ptr );
} }
/// <summary> /// <summary>
@ -390,10 +391,10 @@ namespace lib
/// <remarks> /// <remarks>
/// To free this buffer, call <see cref="FreeMemory"/> /// To free this buffer, call <see cref="FreeMemory"/>
/// </remarks> /// </remarks>
public static IntPtr AllocateClearedMemory(int sizeInBytes, byte clearValue = 0, int align = 16) public static IntPtr AllocateClearedMemory( int sizeInBytes, byte clearValue = 0, int align = 16 )
{ {
var ptr = AllocateMemory(sizeInBytes, align); var ptr = AllocateMemory(sizeInBytes, align);
ClearMemory(ptr, clearValue, sizeInBytes); ClearMemory( ptr, clearValue, sizeInBytes );
return ptr; return ptr;
} }
@ -403,9 +404,9 @@ namespace lib
/// <param name="memoryPtr">The memory pointer.</param> /// <param name="memoryPtr">The memory pointer.</param>
/// <param name="align">The align.</param> /// <param name="align">The align.</param>
/// <returns><c>true</c> if the specified memory pointer is aligned in memory; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if the specified memory pointer is aligned in memory; otherwise, <c>false</c>.</returns>
public static bool IsMemoryAligned(IntPtr memoryPtr, int align = 16) public static bool IsMemoryAligned( IntPtr memoryPtr, int align = 16 )
{ {
return (memoryPtr.ToInt64() & (align - 1)) == 0; return ( memoryPtr.ToInt64() & ( align - 1 ) ) == 0;
} }
/// <summary> /// <summary>
@ -414,18 +415,18 @@ namespace lib
/// <remarks> /// <remarks>
/// The buffer must have been allocated with <see cref="AllocateMemory"/> /// The buffer must have been allocated with <see cref="AllocateMemory"/>
/// </remarks> /// </remarks>
public static unsafe void FreeMemory(IntPtr alignedBuffer) public static unsafe void FreeMemory( IntPtr alignedBuffer )
{ {
Marshal.FreeHGlobal(((IntPtr*)alignedBuffer)[-1]); Marshal.FreeHGlobal( ( (IntPtr*)alignedBuffer )[-1] );
} }
/// <summary> /// <summary>
/// If non-null, disposes the specified object and set it to null, otherwise do nothing. /// If non-null, disposes the specified object and set it to null, otherwise do nothing.
/// </summary> /// </summary>
/// <param name="disposable">The disposable.</param> /// <param name="disposable">The disposable.</param>
public static void Dispose<T>(ref T disposable) where T : class, IDisposable public static void Dispose<T>( ref T disposable ) where T : class, IDisposable
{ {
if (disposable != null) if( disposable != null )
{ {
disposable.Dispose(); disposable.Dispose();
disposable = null; disposable = null;
@ -439,15 +440,16 @@ namespace lib
/// <param name="array">The array.</param> /// <param name="array">The array.</param>
/// <returns>a string with array elements serparated by the seperator</returns> /// <returns>a string with array elements serparated by the seperator</returns>
[NotNull] [NotNull]
public static string Join<T>(string separator, T[] array) public static string Join<T>( string separator, T[] array )
{ {
var text = new StringBuilder(); var text = new StringBuilder();
if (array != null) if( array != null )
{ {
for (var i = 0; i < array.Length; i++) for( var i = 0; i < array.Length; i++ )
{ {
if (i > 0) text.Append(separator); if( i > 0 )
text.Append(array[i]); text.Append( separator );
text.Append( array[i] );
} }
} }
return text.ToString(); return text.ToString();
@ -460,18 +462,19 @@ namespace lib
/// <param name="elements">The enumerable.</param> /// <param name="elements">The enumerable.</param>
/// <returns>a string with array elements serparated by the seperator</returns> /// <returns>a string with array elements serparated by the seperator</returns>
[NotNull] [NotNull]
public static string Join(string separator, [NotNull] IEnumerable elements) public static string Join( string separator, [NotNull] IEnumerable elements )
{ {
var elementList = new List<string>(); var elementList = new List<string>();
foreach (var element in elements) foreach( var element in elements )
elementList.Add(element.ToString()); elementList.Add( element.ToString() );
var text = new StringBuilder(); var text = new StringBuilder();
for (var i = 0; i < elementList.Count; i++) for( var i = 0; i < elementList.Count; i++ )
{ {
var element = elementList[i]; var element = elementList[i];
if (i > 0) text.Append(separator); if( i > 0 )
text.Append(element); text.Append( separator );
text.Append( element );
} }
return text.ToString(); return text.ToString();
} }
@ -483,18 +486,19 @@ namespace lib
/// <param name="elements">The enumerable.</param> /// <param name="elements">The enumerable.</param>
/// <returns>a string with array elements serparated by the seperator</returns> /// <returns>a string with array elements serparated by the seperator</returns>
[NotNull] [NotNull]
public static string Join(string separator, [NotNull] IEnumerator elements) public static string Join( string separator, [NotNull] IEnumerator elements )
{ {
var elementList = new List<string>(); var elementList = new List<string>();
while (elements.MoveNext()) while( elements.MoveNext() )
elementList.Add(elements.Current.ToString()); elementList.Add( elements.Current.ToString() );
var text = new StringBuilder(); var text = new StringBuilder();
for (var i = 0; i < elementList.Count; i++) for( var i = 0; i < elementList.Count; i++ )
{ {
var element = elementList[i]; var element = elementList[i];
if (i > 0) text.Append(separator); if( i > 0 )
text.Append(element); text.Append( separator );
text.Append( element );
} }
return text.ToString(); return text.ToString();
} }
@ -505,10 +509,10 @@ namespace lib
/// <param name = "stream">input stream</param> /// <param name = "stream">input stream</param>
/// <returns>a byte[] buffer</returns> /// <returns>a byte[] buffer</returns>
[NotNull] [NotNull]
public static byte[] ReadStream([NotNull] Stream stream) public static byte[] ReadStream( [NotNull] Stream stream )
{ {
var readLength = 0; var readLength = 0;
return ReadStream(stream, ref readLength); return ReadStream( stream, ref readLength );
} }
/// <summary> /// <summary>
@ -518,28 +522,28 @@ namespace lib
/// <param name = "readLength">length to read</param> /// <param name = "readLength">length to read</param>
/// <returns>a byte[] buffer</returns> /// <returns>a byte[] buffer</returns>
[NotNull] [NotNull]
public static byte[] ReadStream([NotNull] Stream stream, ref int readLength) public static byte[] ReadStream( [NotNull] Stream stream, ref int readLength )
{ {
System.Diagnostics.Debug.Assert(stream != null); System.Diagnostics.Debug.Assert( stream != null );
System.Diagnostics.Debug.Assert(stream.CanRead); System.Diagnostics.Debug.Assert( stream.CanRead );
var num = readLength; var num = readLength;
System.Diagnostics.Debug.Assert(num <= (stream.Length - stream.Position)); System.Diagnostics.Debug.Assert( num <= ( stream.Length - stream.Position ) );
if (num == 0) if( num == 0 )
readLength = (int)(stream.Length - stream.Position); readLength = (int)( stream.Length - stream.Position );
num = readLength; num = readLength;
System.Diagnostics.Debug.Assert(num >= 0); System.Diagnostics.Debug.Assert( num >= 0 );
if (num == 0) if( num == 0 )
return new byte[0]; return new byte[0];
var buffer = new byte[num]; var buffer = new byte[num];
var bytesRead = 0; var bytesRead = 0;
if (num > 0) if( num > 0 )
{ {
do do
{ {
bytesRead += stream.Read(buffer, bytesRead, readLength - bytesRead); bytesRead += stream.Read( buffer, bytesRead, readLength - bytesRead );
} while (bytesRead < readLength); } while( bytesRead < readLength );
} }
return buffer; return buffer;
} }
@ -548,16 +552,16 @@ namespace lib
/// Computes a hashcode for a dictionary. /// Computes a hashcode for a dictionary.
/// </summary> /// </summary>
/// <returns>Hashcode for the list.</returns> /// <returns>Hashcode for the list.</returns>
public static int GetHashCode(IDictionary dict) public static int GetHashCode( IDictionary dict )
{ {
if (dict == null) if( dict == null )
return 0; return 0;
var hashCode = 0; var hashCode = 0;
foreach (DictionaryEntry keyValue in dict) foreach( DictionaryEntry keyValue in dict )
{ {
hashCode = (hashCode * 397) ^ keyValue.Key.GetHashCode(); hashCode = ( hashCode * 397 ) ^ keyValue.Key.GetHashCode();
hashCode = (hashCode * 397) ^ (keyValue.Value?.GetHashCode() ?? 0); hashCode = ( hashCode * 397 ) ^ ( keyValue.Value?.GetHashCode() ?? 0 );
} }
return hashCode; return hashCode;
} }
@ -567,15 +571,15 @@ namespace lib
/// </summary> /// </summary>
/// <param name="it">An enumerator.</param> /// <param name="it">An enumerator.</param>
/// <returns>Hashcode for the list.</returns> /// <returns>Hashcode for the list.</returns>
public static int GetHashCode(IEnumerable it) public static int GetHashCode( IEnumerable it )
{ {
if (it == null) if( it == null )
return 0; return 0;
var hashCode = 0; var hashCode = 0;
foreach (var current in it) foreach( var current in it )
{ {
hashCode = (hashCode * 397) ^ (current?.GetHashCode() ?? 0); hashCode = ( hashCode * 397 ) ^ ( current?.GetHashCode() ?? 0 );
} }
return hashCode; return hashCode;
} }
@ -585,16 +589,16 @@ namespace lib
/// </summary> /// </summary>
/// <param name="it">An enumerator.</param> /// <param name="it">An enumerator.</param>
/// <returns>Hashcode for the list.</returns> /// <returns>Hashcode for the list.</returns>
public static int GetHashCode(IEnumerator it) public static int GetHashCode( IEnumerator it )
{ {
if (it == null) if( it == null )
return 0; return 0;
var hashCode = 0; var hashCode = 0;
while (it.MoveNext()) while( it.MoveNext() )
{ {
var current = it.Current; var current = it.Current;
hashCode = (hashCode * 397) ^ (current?.GetHashCode() ?? 0); hashCode = ( hashCode * 397 ) ^ ( current?.GetHashCode() ?? 0 );
} }
return hashCode; return hashCode;
} }
@ -605,14 +609,14 @@ namespace lib
/// <param name="left">A "from" enumerator.</param> /// <param name="left">A "from" enumerator.</param>
/// <param name="right">A "to" enumerator.</param> /// <param name="right">A "to" enumerator.</param>
/// <returns>True if lists are identical. False otherwise.</returns> /// <returns>True if lists are identical. False otherwise.</returns>
public static bool Compare(IEnumerable left, IEnumerable right) public static bool Compare( IEnumerable left, IEnumerable right )
{ {
if (ReferenceEquals(left, right)) if( ReferenceEquals( left, right ) )
return true; return true;
if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) if( ReferenceEquals( left, null ) || ReferenceEquals( right, null ) )
return false; return false;
return Compare(left.GetEnumerator(), right.GetEnumerator()); return Compare( left.GetEnumerator(), right.GetEnumerator() );
} }
/// <summary> /// <summary>
@ -621,28 +625,28 @@ namespace lib
/// <param name="leftIt">A "from" enumerator.</param> /// <param name="leftIt">A "from" enumerator.</param>
/// <param name="rightIt">A "to" enumerator.</param> /// <param name="rightIt">A "to" enumerator.</param>
/// <returns>True if lists are identical. False otherwise.</returns> /// <returns>True if lists are identical. False otherwise.</returns>
public static bool Compare(IEnumerator leftIt, IEnumerator rightIt) public static bool Compare( IEnumerator leftIt, IEnumerator rightIt )
{ {
if (ReferenceEquals(leftIt, rightIt)) if( ReferenceEquals( leftIt, rightIt ) )
return true; return true;
if (ReferenceEquals(leftIt, null) || ReferenceEquals(rightIt, null)) if( ReferenceEquals( leftIt, null ) || ReferenceEquals( rightIt, null ) )
return false; return false;
bool hasLeftNext; bool hasLeftNext;
bool hasRightNext; bool hasRightNext;
while (true) while( true )
{ {
hasLeftNext = leftIt.MoveNext(); hasLeftNext = leftIt.MoveNext();
hasRightNext = rightIt.MoveNext(); hasRightNext = rightIt.MoveNext();
if (!hasLeftNext || !hasRightNext) if( !hasLeftNext || !hasRightNext )
break; break;
if (!Equals(leftIt.Current, rightIt.Current)) if( !Equals( leftIt.Current, rightIt.Current ) )
return false; return false;
} }
// If there is any left element // If there is any left element
if (hasLeftNext != hasRightNext) if( hasLeftNext != hasRightNext )
return false; return false;
return true; return true;
@ -654,39 +658,44 @@ namespace lib
/// <param name="first">The collection to compare from.</param> /// <param name="first">The collection to compare from.</param>
/// <param name="second">The colllection to compare to.</param> /// <param name="second">The colllection to compare to.</param>
/// <returns>True if lists are identical (but no necessarely of the same time). False otherwise.</returns> /// <returns>True if lists are identical (but no necessarely of the same time). False otherwise.</returns>
public static bool Compare<TKey, TValue>(IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second) public static bool Compare<TKey, TValue>( IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second )
{ {
if (ReferenceEquals(first, second)) return true; if( ReferenceEquals( first, second ) )
if (ReferenceEquals(first, null) || ReferenceEquals(second, null)) return false; return true;
if (first.Count != second.Count) return false; if( ReferenceEquals( first, null ) || ReferenceEquals( second, null ) )
return false;
if( first.Count != second.Count )
return false;
var comparer = EqualityComparer<TValue>.Default; var comparer = EqualityComparer<TValue>.Default;
foreach (var keyValue in first) foreach( var keyValue in first )
{ {
TValue secondValue; TValue secondValue;
if (!second.TryGetValue(keyValue.Key, out secondValue)) return false; if( !second.TryGetValue( keyValue.Key, out secondValue ) )
if (!comparer.Equals(keyValue.Value, secondValue)) return false; return false;
if( !comparer.Equals( keyValue.Value, secondValue ) )
return false;
} }
// Check that all keys in second are in first // Check that all keys in second are in first
return second.Keys.All(first.ContainsKey); return second.Keys.All( first.ContainsKey );
} }
public static bool Compare<T>(T[] left, T[] right) public static bool Compare<T>( T[] left, T[] right )
{ {
if (ReferenceEquals(left, right)) if( ReferenceEquals( left, right ) )
return true; return true;
if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) if( ReferenceEquals( left, null ) || ReferenceEquals( right, null ) )
return false; return false;
if (left.Length != right.Length) if( left.Length != right.Length )
return false; return false;
var comparer = EqualityComparer<T>.Default; var comparer = EqualityComparer<T>.Default;
for (var i = 0; i < left.Length; ++i) for( var i = 0; i < left.Length; ++i )
{ {
if (!comparer.Equals(left[i], right[i])) if( !comparer.Equals( left[i], right[i] ) )
return false; return false;
} }
@ -699,30 +708,30 @@ namespace lib
/// <param name="left">The collection to compare from.</param> /// <param name="left">The collection to compare from.</param>
/// <param name="right">The colllection to compare to.</param> /// <param name="right">The colllection to compare to.</param>
/// <returns>True if lists are identical (but no necessarely of the same time). False otherwise.</returns> /// <returns>True if lists are identical (but no necessarely of the same time). False otherwise.</returns>
public static bool Compare<T>(ICollection<T> left, ICollection<T> right) public static bool Compare<T>( ICollection<T> left, ICollection<T> right )
{ {
if (ReferenceEquals(left, right)) if( ReferenceEquals( left, right ) )
return true; return true;
if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) if( ReferenceEquals( left, null ) || ReferenceEquals( right, null ) )
return false; return false;
if (left.Count != right.Count) if( left.Count != right.Count )
return false; return false;
var count = 0; var count = 0;
var leftIt = left.GetEnumerator(); var leftIt = left.GetEnumerator();
var rightIt = right.GetEnumerator(); var rightIt = right.GetEnumerator();
var comparer = EqualityComparer<T>.Default; var comparer = EqualityComparer<T>.Default;
while (leftIt.MoveNext() && rightIt.MoveNext()) while( leftIt.MoveNext() && rightIt.MoveNext() )
{ {
if (!comparer.Equals(leftIt.Current, rightIt.Current)) if( !comparer.Equals( leftIt.Current, rightIt.Current ) )
return false; return false;
count++; count++;
} }
// Just double check to make sure that the iterator actually returns // Just double check to make sure that the iterator actually returns
// the exact number of elements // the exact number of elements
if (count != left.Count) if( count != left.Count )
return false; return false;
return true; return true;
@ -734,7 +743,7 @@ namespace lib
/// <typeparam name="T">Type of a data to swap.</typeparam> /// <typeparam name="T">Type of a data to swap.</typeparam>
/// <param name="left">The left value.</param> /// <param name="left">The left value.</param>
/// <param name="right">The right value.</param> /// <param name="right">The right value.</param>
public static void Swap<T>(ref T left, ref T right) public static void Swap<T>( ref T left, ref T right )
{ {
var temp = left; var temp = left;
left = right; left = right;
@ -745,12 +754,12 @@ namespace lib
/// Suspends current thread for a <see cref="sleepTime"/>. /// Suspends current thread for a <see cref="sleepTime"/>.
/// </summary> /// </summary>
/// <param name="sleepTime">The duration of sleep.</param> /// <param name="sleepTime">The duration of sleep.</param>
public static void Sleep(TimeSpan sleepTime) public static void Sleep( TimeSpan sleepTime )
{ {
var ms = (long)sleepTime.TotalMilliseconds; var ms = (long)sleepTime.TotalMilliseconds;
if (ms < 0 || ms > int.MaxValue) if( ms < 0 || ms > int.MaxValue )
{ {
throw new ArgumentOutOfRangeException(nameof(sleepTime), "Sleep time must be a duration less than '2^31 - 1' milliseconds."); throw new ArgumentOutOfRangeException( nameof( sleepTime ), "Sleep time must be a duration less than '2^31 - 1' milliseconds." );
} }
// MH PORTED NativeInvoke.Sleep((int)ms); // MH PORTED NativeInvoke.Sleep((int)ms);
Thread.Sleep( (int)ms ); Thread.Sleep( (int)ms );
@ -760,7 +769,7 @@ namespace lib
/// Suspends current thread for a <see cref="sleepTimeInMillis"/>. /// Suspends current thread for a <see cref="sleepTimeInMillis"/>.
/// </summary> /// </summary>
/// <param name="sleepTimeInMillis">The duration of sleep in milliseconds.</param> /// <param name="sleepTimeInMillis">The duration of sleep in milliseconds.</param>
public static void Sleep(int sleepTimeInMillis) public static void Sleep( int sleepTimeInMillis )
{ {
// MH PORTED NativeInvoke.Sleep(sleepTimeInMillis); // MH PORTED NativeInvoke.Sleep(sleepTimeInMillis);
Thread.Sleep( sleepTimeInMillis ); Thread.Sleep( sleepTimeInMillis );
@ -772,11 +781,11 @@ namespace lib
/// <typeparam name="T">Type of a data to write</typeparam> /// <typeparam name="T">Type of a data to write</typeparam>
/// <param name="destination">Memory location to write to.</param> /// <param name="destination">Memory location to write to.</param>
/// <param name="data">The data to write.</param> /// <param name="data">The data to write.</param>
internal static void UnsafeWrite<T>(IntPtr destination, ref T data) internal static void UnsafeWrite<T>( IntPtr destination, ref T data )
{ {
unsafe unsafe
{ {
Interop.CopyInline((void*)destination, ref data); Interop.CopyInline( (void*)destination, ref data );
} }
} }
@ -786,11 +795,11 @@ namespace lib
/// <typeparam name="T">Type of a data to read</typeparam> /// <typeparam name="T">Type of a data to read</typeparam>
/// <param name="source">Memory location to read from.</param> /// <param name="source">Memory location to read from.</param>
/// <param name="data">The data write to.</param> /// <param name="data">The data write to.</param>
internal static void UnsafeReadOut<T>(IntPtr source, out T data) internal static void UnsafeReadOut<T>( IntPtr source, out T data )
{ {
unsafe unsafe
{ {
Interop.CopyInlineOut(out data, (void*)source); Interop.CopyInlineOut( out data, (void*)source );
} }
} }
@ -811,14 +820,14 @@ namespace lib
/// <typeparam name="T">The type to iterate.</typeparam> /// <typeparam name="T">The type to iterate.</typeparam>
/// <param name="root">The root item</param> /// <param name="root">The root item</param>
/// <param name="childrenF">The function to retrieve a child</param> /// <param name="childrenF">The function to retrieve a child</param>
public static IEnumerable<T> IterateTree<T>(T root, Func<T, IEnumerable<T>> childrenF) public static IEnumerable<T> IterateTree<T>( T root, Func<T, IEnumerable<T>> childrenF )
{ {
var q = new List<T> { root }; var q = new List<T> { root };
while (q.Any()) while( q.Any() )
{ {
var c = q[0]; var c = q[0];
q.RemoveAt(0); q.RemoveAt( 0 );
q.AddRange(childrenF(c) ?? Enumerable.Empty<T>()); q.AddRange( childrenF( c ) ?? Enumerable.Empty<T>() );
yield return c; yield return c;
} }
} }
@ -828,9 +837,9 @@ namespace lib
/// </summary> /// </summary>
/// <param name="delta">The delta.</param> /// <param name="delta">The delta.</param>
/// <returns>The <see cref="TimeSpan" />.</returns> /// <returns>The <see cref="TimeSpan" />.</returns>
public static TimeSpan ConvertRawToTimestamp(long delta) public static TimeSpan ConvertRawToTimestamp( long delta )
{ {
return new TimeSpan(delta == 0 ? 0 : (delta * TimeSpan.TicksPerSecond) / Stopwatch.Frequency); return new TimeSpan( delta == 0 ? 0 : ( delta * TimeSpan.TicksPerSecond ) / Stopwatch.Frequency );
} }
} }
} }

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 );
} }
} }
@ -299,7 +299,7 @@ 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;
} }
@ -308,7 +308,7 @@ namespace lib
{ {
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
@ -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 );
} }

View File

@ -25,22 +25,22 @@ namespace lib
IDataContractSurrogate m_surrogate; IDataContractSurrogate m_surrogate;
//int m_maxItems; //int m_maxItems;
public XmlFormatter () public XmlFormatter()
{ {
} }
public XmlFormatter (SerializationMode mode) public XmlFormatter( SerializationMode mode )
{ {
m_mode = mode; m_mode = mode;
} }
public XmlFormatter (StreamingContext context) public XmlFormatter( StreamingContext context )
{ {
m_context = context; m_context = context;
} }
public XmlFormatter (SerializationMode mode, public XmlFormatter( SerializationMode mode,
StreamingContext context) StreamingContext context )
{ {
m_mode = mode; m_mode = mode;
m_context = context; m_context = context;
@ -51,22 +51,26 @@ namespace lib
//{ //{
//} //}
SerializationBinder IFormatter.Binder { SerializationBinder IFormatter.Binder
get { throw new NotImplementedException (); } {
set { throw new NotImplementedException (); } get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
} }
ISurrogateSelector IFormatter.SurrogateSelector { ISurrogateSelector IFormatter.SurrogateSelector
get { throw new NotImplementedException (); } {
set { throw new NotImplementedException (); } get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
} }
public StreamingContext Context { public StreamingContext Context
{
get { return m_context; } get { return m_context; }
set { m_context = value; } set { m_context = value; }
} }
public IDataContractSurrogate DataContractSurrogate { public IDataContractSurrogate DataContractSurrogate
{
get { return m_surrogate; } get { return m_surrogate; }
set { m_surrogate = value; } set { m_surrogate = value; }
} }
@ -82,28 +86,29 @@ namespace lib
} }
*/ */
public SerializationMode Mode { public SerializationMode Mode
{
get { return m_mode; } get { return m_mode; }
} }
object IFormatter.Deserialize (Stream stream) object IFormatter.Deserialize( Stream stream )
{ {
return Deserialize (stream, null); return Deserialize( stream, null );
} }
public object Deserialize (Stream stream, Type type) public object Deserialize( Stream stream, Type type )
{ {
XmlTextReader reader = new XmlTextReader( stream ); XmlTextReader reader = new XmlTextReader( stream );
return Deserialize( reader, type ); return Deserialize( reader, type );
} }
public object Deserialize (XmlReader reader, Type type) public object Deserialize( XmlReader reader, Type type )
{ {
return Deserialize( reader, type, false ); return Deserialize( reader, type, false );
} }
public object Deserialize (XmlReader reader, Type type, bool readContentOnly) public object Deserialize( XmlReader reader, Type type, bool readContentOnly )
{ {
reader.Read(); reader.Read();
@ -192,11 +197,11 @@ namespace lib
{ {
childObj = Deserialize( child ); childObj = Deserialize( child );
m_alreadySerialized[ refInt ] = childObj; m_alreadySerialized[refInt] = childObj;
} }
else else
{ {
childObj = m_alreadySerialized[ refInt ]; childObj = m_alreadySerialized[refInt];
} }
} }
else else
@ -283,15 +288,15 @@ namespace lib
writer.Close(); writer.Close();
} }
public void Serialize (XmlWriter writer, object graph) public void Serialize( XmlWriter writer, object graph )
{ {
Serialize (writer, graph, null, true, false, true); Serialize( writer, graph, null, true, false, true );
} }
public void Serialize (XmlWriter writer, object graph, public void Serialize( XmlWriter writer, object graph,
Type rootType, bool preserveObjectReferences, Type rootType, bool preserveObjectReferences,
bool writeContentOnly, bool writeContentOnly,
bool ignoreUnknownSerializationData) bool ignoreUnknownSerializationData )
{ {
Type t = graph.GetType(); Type t = graph.GetType();
@ -347,7 +352,7 @@ namespace lib
bool first = false; bool first = false;
if( !m_alreadyDeserialzied.ContainsKey( m_idGenerator.GetId( obj, out first ) ) ) if( !m_alreadyDeserialzied.ContainsKey( m_idGenerator.GetId( obj, out first ) ) )
{ {
m_alreadyDeserialzied[ m_idGenerator.GetId( obj, out first ) ] = obj; m_alreadyDeserialzied[m_idGenerator.GetId( obj, out first )] = obj;
Assembly assem = t.Assembly; Assembly assem = t.Assembly;
@ -380,7 +385,7 @@ namespace lib
for( int i = 0; i < arr.Length; ++i ) for( int i = 0; i < arr.Length; ++i )
{ {
Serialize( writer, "val", arr.GetValue(i) ); Serialize( writer, "val", arr.GetValue( i ) );
} }
//writer.WriteStartElement( "values" ); //writer.WriteStartElement( "values" );
@ -431,12 +436,12 @@ namespace lib
/* /*
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public class XmlFormatter : IFormatter public class XmlFormatter : IFormatter
{ {
public enum ETypes public enum ETypes
{ {
Array, Array,
@ -1072,8 +1077,8 @@ namespace lib
#endregion Deserialize #endregion Deserialize
} }
*/ */
//} //}

View File

@ -16,26 +16,26 @@ namespace lib
{ {
public interface I_Serialize public interface I_Serialize
{ {
void OnSerialize(); void OnSerialize();
void OnDeserialize( object enclosing ); void OnDeserialize( object enclosing );
} }
public enum Datastructure public enum Datastructure
{ {
Invalid, Invalid,
Tree, Tree,
Full, Full,
} }
public class XmlFormatter2Cfg : Config public class XmlFormatter2Cfg : Config
{ {
public readonly Datastructure datastructure = Datastructure.Full; public readonly Datastructure datastructure = Datastructure.Full;
} }
public class XmlFormatter2 : IFormatter public class XmlFormatter2 : IFormatter
{ {
public StreamingContext Context { get; set; } public StreamingContext Context { get; set; }
static Random s_rnd = new Random(); static Random s_rnd = new Random();
@ -118,7 +118,8 @@ public class XmlFormatter2 : IFormatter
////lib.log.info( "What to deserialize {0}", doc.OuterXml.ToString() ); ////lib.log.info( "What to deserialize {0}", doc.OuterXml.ToString() );
if( t == null ) return Deserialize( doc.DocumentElement ); if( t == null )
return Deserialize( doc.DocumentElement );
return Deserialize( doc.DocumentElement, t ); return Deserialize( doc.DocumentElement, t );
} }
@ -141,11 +142,12 @@ public class XmlFormatter2 : IFormatter
// @@@@: This should go backwards, we tend to lookup our own stuff, then builtins. // @@@@: This should go backwards, we tend to lookup our own stuff, then builtins.
// Also, cache a typename into its assembly. // Also, cache a typename into its assembly.
foreach(Assembly a in assems) foreach( Assembly a in assems )
{ {
type = a.GetType( typename ); type = a.GetType( typename );
if(type != null) break; if( type != null )
break;
} }
if( type == null ) if( type == null )
@ -267,7 +269,8 @@ public class XmlFormatter2 : IFormatter
var typename = elem.GetAttribute( "t" ); var typename = elem.GetAttribute( "t" );
finalType = FindType( typename ); finalType = FindType( typename );
if( finalType == null ) finalType = type; if( finalType == null )
finalType = type;
} }
object obj = createObject( finalType, refInt ); object obj = createObject( finalType, refInt );
@ -318,8 +321,8 @@ public class XmlFormatter2 : IFormatter
IDeserializationCallback objUnOnDeser = obj as IDeserializationCallback; IDeserializationCallback objUnOnDeser = obj as IDeserializationCallback;
mm_consType[ 0 ] = typeof( SerializationInfo ); mm_consType[0] = typeof( SerializationInfo );
mm_consType[ 1 ] = typeof( StreamingContext ); mm_consType[1] = typeof( StreamingContext );
ConstructorInfo serCons = finalType.GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, mm_consType, null ); ConstructorInfo serCons = finalType.GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, mm_consType, null );
mm_args[0] = serInfo; mm_args[0] = serInfo;
@ -449,7 +452,7 @@ public class XmlFormatter2 : IFormatter
if( m_cfg.datastructure == Datastructure.Full && refInt > 0 && m_alreadySerialized.ContainsKey( refInt ) ) if( m_cfg.datastructure == Datastructure.Full && refInt > 0 && m_alreadySerialized.ContainsKey( refInt ) )
{ {
//lib.log.info( "Reusing object for {0}", refInt ); //lib.log.info( "Reusing object for {0}", refInt );
return m_alreadySerialized[ refInt ]; return m_alreadySerialized[refInt];
} }
else else
{ {
@ -503,7 +506,7 @@ public class XmlFormatter2 : IFormatter
if( m_cfg.datastructure == Datastructure.Full && refInt > 0 && m_alreadySerialized.ContainsKey( refInt ) ) if( m_cfg.datastructure == Datastructure.Full && refInt > 0 && m_alreadySerialized.ContainsKey( refInt ) )
{ {
return (Array)m_alreadySerialized[ refInt ]; return (Array)m_alreadySerialized[refInt];
} }
else else
{ {
@ -511,7 +514,7 @@ public class XmlFormatter2 : IFormatter
if( m_cfg.datastructure == Datastructure.Full ) if( m_cfg.datastructure == Datastructure.Full )
{ {
m_alreadySerialized[ refInt ] = arr; m_alreadySerialized[refInt] = arr;
} }
@ -635,7 +638,7 @@ public class XmlFormatter2 : IFormatter
{ {
if( m_cfg.datastructure == Datastructure.Full ) if( m_cfg.datastructure == Datastructure.Full )
{ {
m_alreadySerialized[ refInt ] = root; m_alreadySerialized[refInt] = root;
} }
Type type = root.GetType(); Type type = root.GetType();
@ -716,7 +719,7 @@ public class XmlFormatter2 : IFormatter
{ {
if( m_cfg.datastructure == Datastructure.Full ) if( m_cfg.datastructure == Datastructure.Full )
{ {
m_alreadySerialized[ refInt ] = root; m_alreadySerialized[refInt] = root;
} }
@ -727,6 +730,6 @@ public class XmlFormatter2 : IFormatter
} }
} }
#endregion #endregion
} }
} }

View File

@ -44,7 +44,7 @@ namespace att
[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

@ -18,7 +18,7 @@ namespace att
[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,18 +9,18 @@ using System.Reflection;
namespace mod namespace mod
{ {
[Serializable] [Serializable]
public class Config : lib.Config public class Config : lib.Config
{ {
public String name = "Generic"; public String name = "Generic";
} }
public class View public class View
{ {
} }
public class Base public class Base
{ {
public Config Cfg { get { return m_cfg; } } public Config Cfg { get { return m_cfg; } }
public Base( Config cfg ) public Base( Config cfg )
@ -29,25 +29,25 @@ public class Base
} }
private Config m_cfg; private Config m_cfg;
} }
[Serializable] [Serializable]
public class FluidConfig : Config public class FluidConfig : Config
{ {
public String type = "none"; public String type = "none";
} }
public class FluidBase : Base public class FluidBase : Base
{ {
public new FluidConfig Cfg { get { return (FluidConfig)base.Cfg; } } public new FluidConfig Cfg { get { return (FluidConfig)base.Cfg; } }
public FluidBase( FluidConfig cfg ) public FluidBase( FluidConfig cfg )
: base( cfg ) : base( cfg )
{ {
} }
} }
@ -64,15 +64,15 @@ public class FluidBase : Base
[Serializable] [Serializable]
public class SystemConfig : Config public class SystemConfig : Config
{ {
public String type = "none"; public String type = "none";
} }
public class System public class System
{ {
public SystemConfig Cfg { get { return m_cfg; } } public SystemConfig Cfg { get { return m_cfg; } }
public System( SystemConfig cfg ) public System( SystemConfig cfg )
@ -81,7 +81,7 @@ public class System
} }
private SystemConfig m_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;
} }