diff --git a/.gitignore b/.gitignore index 0f7756c..c0e6415 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,3 @@ -################################### -# Git ignore file for Molyjam2012 # -################################### - #Folders Library/ Temp/ @@ -12,6 +8,7 @@ Release/ run/ bin/ obj/ +.vs/ #Project/User Preference Files *.pidb diff --git a/Helpers.cs b/Helpers.cs index cb448ac..3c5ee7b 100644 --- a/Helpers.cs +++ b/Helpers.cs @@ -1,8 +1,8 @@ - + /* * TODO: Need to verify types are correct when deserializing. -*/ - +*/ + using System; using System.Collections.Generic; using System.Linq; @@ -22,10 +22,10 @@ namespace lib { FileStream fs = new FileStream( filename, FileMode.Create, FileAccess.Write ); - XmlSerializer xs = new XmlSerializer( obj.GetType() ); - //MemoryStream memoryStream = new MemoryStream( StringToUTF8ByteArray( pXmlizedString ) ); - //XmlTextReader reader = new XmlTextReader( fs, Encoding.UTF8 ); - + XmlSerializer xs = new XmlSerializer( obj.GetType() ); + //MemoryStream memoryStream = new MemoryStream( StringToUTF8ByteArray( pXmlizedString ) ); + //XmlTextReader reader = new XmlTextReader( fs, Encoding.UTF8 ); + xs.Serialize( fs, obj ); } @@ -33,10 +33,10 @@ namespace lib { FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read ); - XmlSerializer xs = new XmlSerializer( typeof( TType ) ); - //MemoryStream memoryStream = new MemoryStream( StringToUTF8ByteArray( pXmlizedString ) ); - //XmlTextReader reader = new XmlTextReader( fs, Encoding.UTF8 ); - + XmlSerializer xs = new XmlSerializer( typeof( TType ) ); + //MemoryStream memoryStream = new MemoryStream( StringToUTF8ByteArray( pXmlizedString ) ); + //XmlTextReader reader = new XmlTextReader( fs, Encoding.UTF8 ); + return xs.Deserialize( fs ); } @@ -72,10 +72,10 @@ namespace lib { XmlTextWriter xmlWriter = new XmlTextWriter( filename, null ); - xmlWriter.Formatting = Formatting.Indented; - - //xmlWriter.WriteStartDocument(); - + xmlWriter.Formatting = Formatting.Indented; + + //xmlWriter.WriteStartDocument(); + xmlWriter.WriteStartElement( "dictionary" ); Type[] types = dict.GetType().GetGenericArguments(); @@ -93,10 +93,10 @@ namespace lib xmlWriter.WriteEndElement(); } - xmlWriter.WriteEndElement(); - - //xmlWriter.WriteEndDocument(); - + xmlWriter.WriteEndElement(); + + //xmlWriter.WriteEndDocument(); + xmlWriter.Close(); } @@ -106,10 +106,10 @@ namespace lib XmlDocument doc = new XmlDocument(); - doc.Load( fs ); - - //CreateTypeFor() - + doc.Load( fs ); + + //CreateTypeFor() + XmlElement docElem = doc.DocumentElement; if( docElem.Name == "dictionary" ) @@ -125,10 +125,10 @@ namespace lib { XmlNodeList nodeList = docElem.ChildNodes; - object[] args = new object[ 1 ]; - - //fi.SetValue( newObj, obj ); - + object[] args = new object[ 1 ]; + + //fi.SetValue( newObj, obj ); + foreach( XmlElement node in nodeList ) { if( node.Name == "kvp" ) @@ -147,28 +147,28 @@ namespace lib } else { - Log.error( String.Format( $"No attributes in node while loading file {filename}" ) ); + log.error( String.Format( $"No attributes in node while loading file {filename}" ) ); } } else { - Log.error( String.Format( $"Incorrect key {node.Name} found while loading file {filename}" ) ); + log.error( String.Format( $"Incorrect key {node.Name} found while loading file {filename}" ) ); } } } else { if( keyMI == null ) - Log.error( String.Format( $"Key type conversion not found for type {keyType}" ) ); + log.error( String.Format( $"Key type conversion not found for type {keyType}" ) ); if( valMI == null ) - Log.error( String.Format( $"Val type conversion not found for type {valType}" ) ); + log.error( String.Format( $"Val type conversion not found for type {valType}" ) ); } } else { - Log.error( String.Format( $"No dictionary element found while loading file {filename}" ) ); + log.error( String.Format( $"No dictionary element found while loading file {filename}" ) ); } } diff --git a/Id.cs b/Id.cs index 5954041..2172cdf 100644 --- a/Id.cs +++ b/Id.cs @@ -1,616 +1,616 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Runtime.InteropServices; -using System.Security; -using System.Text; -using System.Threading.Tasks; - -//using System.MemoryExtensions; - -namespace lib -{ - - - public struct Id : IComparable, IFormattable, IConvertible, IComparable, IEquatable - { - public const ulong Min = 0uL; - public const ulong Max = 18446744073709551615uL; - - static Random s_rand = new Random(); - - - // TODO PERF Make span versions of all these functions - - unsafe public static Id Generate() - { - var buf = new byte[8]; - - s_rand.NextBytes( buf ); - - var newId = BitConverter.ToUInt64( buf, 0 ); - - return new Id { m_value = newId }; - } - - ulong m_value; - - - public int CompareTo( object value ) - { - if( value == null ) - { - return 1; - } - if( value is ulong ) - { - ulong num = (ulong)value; - if( m_value < num ) - { - return -1; - } - if( m_value > num ) - { - return 1; - } - return 0; - } - throw new ArgumentException( "" ); - } - - public int CompareTo( ulong value ) - { - if( m_value < value ) - { - return -1; - } - if( m_value > value ) - { - return 1; - } - return 0; - } - - public override bool Equals( object obj ) - { - if( !( obj is ulong ) ) - { - return false; - } - return m_value == (ulong)obj; - } - - public bool Equals( ulong obj ) - { - return m_value == obj; - } - - public override int GetHashCode() - { - return (int)m_value ^ (int)( m_value >> 32 ); - } - - #region ToString - // - // Summary: - // Converts the numeric value of m_value instance to its equivalent string representation. - // - // Returns: - // The string representation of the value of m_value instance, consisting of a sequence - // of digits ranging from 0 to 9, without a sign or leading zeroes. - [SecuritySafeCritical] - - public override string ToString() - { - return m_value.ToString( null, NumberFormatInfo.CurrentInfo ); - } - - // - // Summary: - // Converts the numeric value of m_value instance to its equivalent string representation - // using the specified culture-specific format information. - // - // Parameters: - // provider: - // An object that supplies culture-specific formatting information. - // - // Returns: - // The string representation of the value of m_value instance as specified by provider. - [SecuritySafeCritical] - - public string ToString( IFormatProvider provider ) - { - return m_value.ToString( null, NumberFormatInfo.GetInstance( provider ) ); - } - - // - // Summary: - // Converts the numeric value of m_value instance to its equivalent string representation - // using the specified format. - // - // Parameters: - // format: - // A numeric format string. - // - // Returns: - // The string representation of the value of m_value instance as specified by format. - // - // Exceptions: - // T:System.FormatException: - // The format parameter is invalid. - [SecuritySafeCritical] - - public string ToString( string format ) - { - return m_value.ToString( format, NumberFormatInfo.CurrentInfo ); - } - - // - // Summary: - // Converts the numeric value of m_value instance to its equivalent string representation - // using the specified format and culture-specific format information. - // - // Parameters: - // format: - // A numeric format string. - // - // provider: - // An object that supplies culture-specific formatting information about m_value instance. - // - // Returns: - // The string representation of the value of m_value instance as specified by format - // and provider. - // - // Exceptions: - // T:System.FormatException: - // The format parameter is invalid. - [SecuritySafeCritical] - - public string ToString( string format, IFormatProvider provider ) - { - return m_value.ToString( format, NumberFormatInfo.GetInstance( provider ) ); - } - - #endregion - - #region Parse - // - // Summary: - // Converts the string representation of a number to its 64-bit unsigned integer - // equivalent. - // - // Parameters: - // s: - // A string that represents the number to convert. - // - // Returns: - // A 64-bit unsigned integer equivalent to the number contained in s. - // - // Exceptions: - // T:System.ArgumentNullException: - // The s parameter is null. - // - // T:System.FormatException: - // The s parameter is not in the correct format. - // - // T:System.OverflowException: - // The s parameter represents a number less than System.UInt64.MinValue or greater - // than System.UInt64.MaxValue. - - - public static ulong Parse( string s ) - { - - return ulong.Parse( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo ); - } - - // - // Summary: - // Converts the string representation of a number in a specified style to its 64-bit - // unsigned integer equivalent. - // - // Parameters: - // s: - // A string that represents the number to convert. The string is interpreted by - // using the style specified by the style parameter. - // - // style: - // A bitwise combination of the enumeration values that specifies the permitted - // format of s. A typical value to specify is System.Globalization.NumberStyles.Integer. - // - // Returns: - // A 64-bit unsigned integer equivalent to the number specified in s. - // - // Exceptions: - // T:System.ArgumentNullException: - // The s parameter is null. - // - // T:System.ArgumentException: - // /// style is not a System.Globalization.NumberStyles value. -or-style is not - // a combination of System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber - // values. - // - // T:System.FormatException: - // The s parameter is not in a format compliant with style. - // - // T:System.OverflowException: - // The s parameter represents a number less than System.UInt64.MinValue or greater - // than System.UInt64.MaxValue. -or-s includes non-zero, fractional digits. - - - public static ulong Parse( string s, NumberStyles style ) - { - return ulong.Parse( s, style, NumberFormatInfo.CurrentInfo ); - } - - // - // Summary: - // Converts the string representation of a number in a specified culture-specific - // format to its 64-bit unsigned integer equivalent. - // - // Parameters: - // s: - // A string that represents the number to convert. - // - // provider: - // An object that supplies culture-specific formatting information about s. - // - // Returns: - // A 64-bit unsigned integer equivalent to the number specified in s. - // - // Exceptions: - // T:System.ArgumentNullException: - // The s parameter is null. - // - // T:System.FormatException: - // The s parameter is not in the correct style. - // - // T:System.OverflowException: - // The s parameter represents a number less than System.UInt64.MinValue or greater - // than System.UInt64.MaxValue. - - - public static ulong Parse( string s, IFormatProvider provider ) - { - return ulong.Parse( s, NumberStyles.Integer, NumberFormatInfo.GetInstance( provider ) ); - } - - // - // Summary: - // Converts the string representation of a number in a specified style and culture-specific - // format to its 64-bit unsigned integer equivalent. - // - // Parameters: - // s: - // A string that represents the number to convert. The string is interpreted by - // using the style specified by the style parameter. - // - // style: - // A bitwise combination of enumeration values that indicates the style elements - // that can be present in s. A typical value to specify is System.Globalization.NumberStyles.Integer. - // - // provider: - // An object that supplies culture-specific formatting information about s. - // - // Returns: - // A 64-bit unsigned integer equivalent to the number specified in s. - // - // Exceptions: - // T:System.ArgumentNullException: - // The s parameter is null. - // - // T:System.ArgumentException: - // /// style is not a System.Globalization.NumberStyles value. -or-style is not - // a combination of System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber - // values. - // - // T:System.FormatException: - // The s parameter is not in a format compliant with style. - // - // T:System.OverflowException: - // The s parameter represents a number less than System.UInt64.MinValue or greater - // than System.UInt64.MaxValue. -or-s includes non-zero, fractional digits. - - - public static ulong Parse( string s, NumberStyles style, IFormatProvider provider ) - { - return ulong.Parse( s, style, NumberFormatInfo.GetInstance( provider ) ); - } - - // - // Summary: - // Tries to convert the string representation of a number to its 64-bit unsigned - // integer equivalent. A return value indicates whether the conversion succeeded - // or failed. - // - // Parameters: - // s: - // A string that represents the number to convert. - // - // result: - // When m_value method returns, contains the 64-bit unsigned integer value that is - // equivalent to the number contained in s, if the conversion succeeded, or zero - // if the conversion failed. The conversion fails if the s parameter is null, is - // not of the correct format, or represents a number less than System.UInt64.MinValue - // or greater than System.UInt64.MaxValue. m_value parameter is passed uninitialized. - // - // Returns: - // true if s was converted successfully; otherwise, false. - - - public static bool TryParse( string s, out ulong result ) - { - return ulong.TryParse( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result ); - } - - // - // Summary: - // Tries to convert the string representation of a number in a specified style and - // culture-specific format to its 64-bit unsigned integer equivalent. A return value - // indicates whether the conversion succeeded or failed. - // - // Parameters: - // s: - // A string that represents the number to convert. The string is interpreted by - // using the style specified by the style parameter. - // - // style: - // A bitwise combination of enumeration values that indicates the permitted format - // of s. A typical value to specify is System.Globalization.NumberStyles.Integer. - // - // provider: - // An object that supplies culture-specific formatting information about s. - // - // result: - // When m_value method returns, contains the 64-bit unsigned integer value equivalent - // to the number contained in s, if the conversion succeeded, or zero if the conversion - // failed. The conversion fails if the s parameter is null, is not in a format compliant - // with style, or represents a number less than System.UInt64.MinValue or greater - // than System.UInt64.MaxValue. m_value parameter is passed uninitialized. - // - // Returns: - // true if s was converted successfully; otherwise, false. - // - // Exceptions: - // T:System.ArgumentException: - // /// style is not a System.Globalization.NumberStyles value. -or-style is not - // a combination of System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber - // values. - - - public static bool TryParse( string s, NumberStyles style, IFormatProvider provider, out ulong result ) - { - return ulong.TryParse( s, style, NumberFormatInfo.GetInstance( provider ), out result ); - } - - #endregion - - - // - // Summary: - // Returns the System.TypeCode for value type System.UInt64. - // - // Returns: - // The enumerated constant, System.TypeCode.UInt64. - public TypeCode GetTypeCode() - { - return TypeCode.UInt64; - } - - #region Converters - // - // Summary: - // For a description of m_value member, see System.IConvertible.ToBoolean(System.IFormatProvider). - // - // Parameters: - // provider: - // m_value parameter is ignored. - // - // Returns: - // true if the value of the current instance is not zero; otherwise, false. - - bool IConvertible.ToBoolean( IFormatProvider provider ) - { - return Convert.ToBoolean( m_value ); - } - - // - // Summary: - // For a description of m_value member, see System.IConvertible.ToChar(System.IFormatProvider). - // - // Parameters: - // provider: - // m_value parameter is ignored. - // - // Returns: - // The value of the current instance, converted to a System.Char. - - char IConvertible.ToChar( IFormatProvider provider ) - { - return Convert.ToChar( m_value ); - } - - // - // Summary: - // For a description of m_value member, see System.IConvertible.ToSByte(System.IFormatProvider). - // - // Parameters: - // provider: - // m_value parameter is ignored. - // - // Returns: - // The value of the current instance, converted to an System.SByte. - - sbyte IConvertible.ToSByte( IFormatProvider provider ) - { - return Convert.ToSByte( m_value ); - } - - // - // Summary: - // For a description of m_value member, see System.IConvertible.ToByte(System.IFormatProvider). - // - // Parameters: - // provider: - // m_value parameter is ignored. - // - // Returns: - // The value of the current instance, converted to a System.Byte. - - byte IConvertible.ToByte( IFormatProvider provider ) - { - return Convert.ToByte( m_value ); - } - - // - // Summary: - // For a description of m_value member, see System.IConvertible.ToInt16(System.IFormatProvider). - // - // Parameters: - // provider: - // m_value parameter is ignored. - // - // Returns: - // The value of the current instance, converted to an System.Int16. - - short IConvertible.ToInt16( IFormatProvider provider ) - { - return Convert.ToInt16( m_value ); - } - - // - // Summary: - // For a description of m_value member, see System.IConvertible.ToUInt16(System.IFormatProvider). - // - // Parameters: - // provider: - // m_value parameter is ignored. - // - // Returns: - // The value of the current instance, converted to a System.UInt16. - - ushort IConvertible.ToUInt16( IFormatProvider provider ) - { - return Convert.ToUInt16( m_value ); - } - - // - // Summary: - // For a description of m_value member, see System.IConvertible.ToInt32(System.IFormatProvider). - // - // Parameters: - // provider: - // m_value parameter is ignored. - // - // Returns: - // The value of the current instance, converted to an System.Int32. - - int IConvertible.ToInt32( IFormatProvider provider ) - { - return Convert.ToInt32( m_value ); - } - - // - // Summary: - // For a description of m_value member, see System.IConvertible.ToUInt32(System.IFormatProvider). - // - // Parameters: - // provider: - // m_value parameter is ignored. - // - // Returns: - // The value of the current instance, converted to a System.UInt32. - - uint IConvertible.ToUInt32( IFormatProvider provider ) - { - return Convert.ToUInt32( m_value ); - } - - // - // Summary: - // For a description of m_value member, see System.IConvertible.ToInt64(System.IFormatProvider). - // - // Parameters: - // provider: - // m_value parameter is ignored. - // - // Returns: - // The value of the current instance, converted to an System.Int64. - - long IConvertible.ToInt64( IFormatProvider provider ) - { - return Convert.ToInt64( m_value ); - } - - // - // Summary: - // For a description of m_value member, see System.IConvertible.ToUInt64(System.IFormatProvider). - // - // Parameters: - // provider: - // m_value parameter is ignored. - // - // Returns: - // The value of the current instance, unchanged. - - ulong IConvertible.ToUInt64( IFormatProvider provider ) - { - return m_value; - } - - // - // Summary: - // For a description of m_value member, see System.IConvertible.ToSingle(System.IFormatProvider). - // - // Parameters: - // provider: - // m_value parameter is ignored. - // - // Returns: - // The value of the current instance, converted to a System.Single. - - float IConvertible.ToSingle( IFormatProvider provider ) - { - return Convert.ToSingle( m_value ); - } - - // - // Summary: - // For a description of m_value member, see System.IConvertible.ToDouble(System.IFormatProvider). - // - // Parameters: - // provider: - // m_value parameter is ignored. - // - // Returns: - // The value of the current instance, converted to a System.Double. - - double IConvertible.ToDouble( IFormatProvider provider ) - { - return Convert.ToDouble( m_value ); - } - - decimal IConvertible.ToDecimal( IFormatProvider provider ) - { - return Convert.ToDecimal( m_value ); - } - - DateTime IConvertible.ToDateTime( IFormatProvider provider ) - { - throw new InvalidCastException( $"InvalidCast_FromTo UInt64 DateTime" ); - } - - public object ToType( Type conversionType, IFormatProvider provider ) - { - return Convert.ChangeType( m_value, conversionType, provider ); - } - - #endregion - - } - - - - -} +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Runtime.InteropServices; +using System.Security; +using System.Text; +using System.Threading.Tasks; + +//using System.MemoryExtensions; + +namespace lib +{ + + + public struct Id: IComparable, IFormattable, IConvertible, IComparable, IEquatable + { + public const ulong Min = 0uL; + public const ulong Max = 18446744073709551615uL; + + static Random s_rand = new Random(); + + + // TODO PERF Make span versions of all these functions + + unsafe public static Id Generate() + { + var buf = new byte[8]; + + s_rand.NextBytes( buf ); + + var newId = BitConverter.ToUInt64(buf, 0); + + return new Id { m_value = newId }; + } + + ulong m_value; + + + public int CompareTo( object value ) + { + if( value == null ) + { + return 1; + } + if( value is ulong ) + { + ulong num = (ulong)value; + if( m_value < num ) + { + return -1; + } + if( m_value > num ) + { + return 1; + } + return 0; + } + throw new ArgumentException( "" ); + } + + public int CompareTo( ulong value ) + { + if( m_value < value ) + { + return -1; + } + if( m_value > value ) + { + return 1; + } + return 0; + } + + public override bool Equals( object obj ) + { + if( !( obj is ulong ) ) + { + return false; + } + return m_value == (ulong)obj; + } + + public bool Equals( ulong obj ) + { + return m_value == obj; + } + + public override int GetHashCode() + { + return (int)m_value ^ (int)( m_value >> 32 ); + } + + #region ToString + // + // Summary: + // Converts the numeric value of m_value instance to its equivalent string representation. + // + // Returns: + // The string representation of the value of m_value instance, consisting of a sequence + // of digits ranging from 0 to 9, without a sign or leading zeroes. + [SecuritySafeCritical] + + public override string ToString() + { + return m_value.ToString( null, NumberFormatInfo.CurrentInfo ); + } + + // + // Summary: + // Converts the numeric value of m_value instance to its equivalent string representation + // using the specified culture-specific format information. + // + // Parameters: + // provider: + // An object that supplies culture-specific formatting information. + // + // Returns: + // The string representation of the value of m_value instance as specified by provider. + [SecuritySafeCritical] + + public string ToString( IFormatProvider provider ) + { + return m_value.ToString( null, NumberFormatInfo.GetInstance( provider ) ); + } + + // + // Summary: + // Converts the numeric value of m_value instance to its equivalent string representation + // using the specified format. + // + // Parameters: + // format: + // A numeric format string. + // + // Returns: + // The string representation of the value of m_value instance as specified by format. + // + // Exceptions: + // T:System.FormatException: + // The format parameter is invalid. + [SecuritySafeCritical] + + public string ToString( string format ) + { + return m_value.ToString( format, NumberFormatInfo.CurrentInfo ); + } + + // + // Summary: + // Converts the numeric value of m_value instance to its equivalent string representation + // using the specified format and culture-specific format information. + // + // Parameters: + // format: + // A numeric format string. + // + // provider: + // An object that supplies culture-specific formatting information about m_value instance. + // + // Returns: + // The string representation of the value of m_value instance as specified by format + // and provider. + // + // Exceptions: + // T:System.FormatException: + // The format parameter is invalid. + [SecuritySafeCritical] + + public string ToString( string format, IFormatProvider provider ) + { + return m_value.ToString( format, NumberFormatInfo.GetInstance( provider ) ); + } + + #endregion + + #region Parse + // + // Summary: + // Converts the string representation of a number to its 64-bit unsigned integer + // equivalent. + // + // Parameters: + // s: + // A string that represents the number to convert. + // + // Returns: + // A 64-bit unsigned integer equivalent to the number contained in s. + // + // Exceptions: + // T:System.ArgumentNullException: + // The s parameter is null. + // + // T:System.FormatException: + // The s parameter is not in the correct format. + // + // T:System.OverflowException: + // The s parameter represents a number less than System.UInt64.MinValue or greater + // than System.UInt64.MaxValue. + + + public static ulong Parse( string s ) + { + + return ulong.Parse( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo ); + } + + // + // Summary: + // Converts the string representation of a number in a specified style to its 64-bit + // unsigned integer equivalent. + // + // Parameters: + // s: + // A string that represents the number to convert. The string is interpreted by + // using the style specified by the style parameter. + // + // style: + // A bitwise combination of the enumeration values that specifies the permitted + // format of s. A typical value to specify is System.Globalization.NumberStyles.Integer. + // + // Returns: + // A 64-bit unsigned integer equivalent to the number specified in s. + // + // Exceptions: + // T:System.ArgumentNullException: + // The s parameter is null. + // + // T:System.ArgumentException: + // /// style is not a System.Globalization.NumberStyles value. -or-style is not + // a combination of System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber + // values. + // + // T:System.FormatException: + // The s parameter is not in a format compliant with style. + // + // T:System.OverflowException: + // The s parameter represents a number less than System.UInt64.MinValue or greater + // than System.UInt64.MaxValue. -or-s includes non-zero, fractional digits. + + + public static ulong Parse( string s, NumberStyles style ) + { + return ulong.Parse( s, style, NumberFormatInfo.CurrentInfo ); + } + + // + // Summary: + // Converts the string representation of a number in a specified culture-specific + // format to its 64-bit unsigned integer equivalent. + // + // Parameters: + // s: + // A string that represents the number to convert. + // + // provider: + // An object that supplies culture-specific formatting information about s. + // + // Returns: + // A 64-bit unsigned integer equivalent to the number specified in s. + // + // Exceptions: + // T:System.ArgumentNullException: + // The s parameter is null. + // + // T:System.FormatException: + // The s parameter is not in the correct style. + // + // T:System.OverflowException: + // The s parameter represents a number less than System.UInt64.MinValue or greater + // than System.UInt64.MaxValue. + + + public static ulong Parse( string s, IFormatProvider provider ) + { + return ulong.Parse( s, NumberStyles.Integer, NumberFormatInfo.GetInstance( provider ) ); + } + + // + // Summary: + // Converts the string representation of a number in a specified style and culture-specific + // format to its 64-bit unsigned integer equivalent. + // + // Parameters: + // s: + // A string that represents the number to convert. The string is interpreted by + // using the style specified by the style parameter. + // + // style: + // A bitwise combination of enumeration values that indicates the style elements + // that can be present in s. A typical value to specify is System.Globalization.NumberStyles.Integer. + // + // provider: + // An object that supplies culture-specific formatting information about s. + // + // Returns: + // A 64-bit unsigned integer equivalent to the number specified in s. + // + // Exceptions: + // T:System.ArgumentNullException: + // The s parameter is null. + // + // T:System.ArgumentException: + // /// style is not a System.Globalization.NumberStyles value. -or-style is not + // a combination of System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber + // values. + // + // T:System.FormatException: + // The s parameter is not in a format compliant with style. + // + // T:System.OverflowException: + // The s parameter represents a number less than System.UInt64.MinValue or greater + // than System.UInt64.MaxValue. -or-s includes non-zero, fractional digits. + + + public static ulong Parse( string s, NumberStyles style, IFormatProvider provider ) + { + return ulong.Parse( s, style, NumberFormatInfo.GetInstance( provider ) ); + } + + // + // Summary: + // Tries to convert the string representation of a number to its 64-bit unsigned + // integer equivalent. A return value indicates whether the conversion succeeded + // or failed. + // + // Parameters: + // s: + // A string that represents the number to convert. + // + // result: + // When m_value method returns, contains the 64-bit unsigned integer value that is + // equivalent to the number contained in s, if the conversion succeeded, or zero + // if the conversion failed. The conversion fails if the s parameter is null, is + // not of the correct format, or represents a number less than System.UInt64.MinValue + // or greater than System.UInt64.MaxValue. m_value parameter is passed uninitialized. + // + // Returns: + // true if s was converted successfully; otherwise, false. + + + public static bool TryParse( string s, out ulong result ) + { + return ulong.TryParse( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result ); + } + + // + // Summary: + // Tries to convert the string representation of a number in a specified style and + // culture-specific format to its 64-bit unsigned integer equivalent. A return value + // indicates whether the conversion succeeded or failed. + // + // Parameters: + // s: + // A string that represents the number to convert. The string is interpreted by + // using the style specified by the style parameter. + // + // style: + // A bitwise combination of enumeration values that indicates the permitted format + // of s. A typical value to specify is System.Globalization.NumberStyles.Integer. + // + // provider: + // An object that supplies culture-specific formatting information about s. + // + // result: + // When m_value method returns, contains the 64-bit unsigned integer value equivalent + // to the number contained in s, if the conversion succeeded, or zero if the conversion + // failed. The conversion fails if the s parameter is null, is not in a format compliant + // with style, or represents a number less than System.UInt64.MinValue or greater + // than System.UInt64.MaxValue. m_value parameter is passed uninitialized. + // + // Returns: + // true if s was converted successfully; otherwise, false. + // + // Exceptions: + // T:System.ArgumentException: + // /// style is not a System.Globalization.NumberStyles value. -or-style is not + // a combination of System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber + // values. + + + public static bool TryParse( string s, NumberStyles style, IFormatProvider provider, out ulong result ) + { + return ulong.TryParse( s, style, NumberFormatInfo.GetInstance( provider ), out result ); + } + + #endregion + + + // + // Summary: + // Returns the System.TypeCode for value type System.UInt64. + // + // Returns: + // The enumerated constant, System.TypeCode.UInt64. + public TypeCode GetTypeCode() + { + return TypeCode.UInt64; + } + + #region Converters + // + // Summary: + // For a description of m_value member, see System.IConvertible.ToBoolean(System.IFormatProvider). + // + // Parameters: + // provider: + // m_value parameter is ignored. + // + // Returns: + // true if the value of the current instance is not zero; otherwise, false. + + bool IConvertible.ToBoolean( IFormatProvider provider ) + { + return Convert.ToBoolean( m_value ); + } + + // + // Summary: + // For a description of m_value member, see System.IConvertible.ToChar(System.IFormatProvider). + // + // Parameters: + // provider: + // m_value parameter is ignored. + // + // Returns: + // The value of the current instance, converted to a System.Char. + + char IConvertible.ToChar( IFormatProvider provider ) + { + return Convert.ToChar( m_value ); + } + + // + // Summary: + // For a description of m_value member, see System.IConvertible.ToSByte(System.IFormatProvider). + // + // Parameters: + // provider: + // m_value parameter is ignored. + // + // Returns: + // The value of the current instance, converted to an System.SByte. + + sbyte IConvertible.ToSByte( IFormatProvider provider ) + { + return Convert.ToSByte( m_value ); + } + + // + // Summary: + // For a description of m_value member, see System.IConvertible.ToByte(System.IFormatProvider). + // + // Parameters: + // provider: + // m_value parameter is ignored. + // + // Returns: + // The value of the current instance, converted to a System.Byte. + + byte IConvertible.ToByte( IFormatProvider provider ) + { + return Convert.ToByte( m_value ); + } + + // + // Summary: + // For a description of m_value member, see System.IConvertible.ToInt16(System.IFormatProvider). + // + // Parameters: + // provider: + // m_value parameter is ignored. + // + // Returns: + // The value of the current instance, converted to an System.Int16. + + short IConvertible.ToInt16( IFormatProvider provider ) + { + return Convert.ToInt16( m_value ); + } + + // + // Summary: + // For a description of m_value member, see System.IConvertible.ToUInt16(System.IFormatProvider). + // + // Parameters: + // provider: + // m_value parameter is ignored. + // + // Returns: + // The value of the current instance, converted to a System.UInt16. + + ushort IConvertible.ToUInt16( IFormatProvider provider ) + { + return Convert.ToUInt16( m_value ); + } + + // + // Summary: + // For a description of m_value member, see System.IConvertible.ToInt32(System.IFormatProvider). + // + // Parameters: + // provider: + // m_value parameter is ignored. + // + // Returns: + // The value of the current instance, converted to an System.Int32. + + int IConvertible.ToInt32( IFormatProvider provider ) + { + return Convert.ToInt32( m_value ); + } + + // + // Summary: + // For a description of m_value member, see System.IConvertible.ToUInt32(System.IFormatProvider). + // + // Parameters: + // provider: + // m_value parameter is ignored. + // + // Returns: + // The value of the current instance, converted to a System.UInt32. + + uint IConvertible.ToUInt32( IFormatProvider provider ) + { + return Convert.ToUInt32( m_value ); + } + + // + // Summary: + // For a description of m_value member, see System.IConvertible.ToInt64(System.IFormatProvider). + // + // Parameters: + // provider: + // m_value parameter is ignored. + // + // Returns: + // The value of the current instance, converted to an System.Int64. + + long IConvertible.ToInt64( IFormatProvider provider ) + { + return Convert.ToInt64( m_value ); + } + + // + // Summary: + // For a description of m_value member, see System.IConvertible.ToUInt64(System.IFormatProvider). + // + // Parameters: + // provider: + // m_value parameter is ignored. + // + // Returns: + // The value of the current instance, unchanged. + + ulong IConvertible.ToUInt64( IFormatProvider provider ) + { + return m_value; + } + + // + // Summary: + // For a description of m_value member, see System.IConvertible.ToSingle(System.IFormatProvider). + // + // Parameters: + // provider: + // m_value parameter is ignored. + // + // Returns: + // The value of the current instance, converted to a System.Single. + + float IConvertible.ToSingle( IFormatProvider provider ) + { + return Convert.ToSingle( m_value ); + } + + // + // Summary: + // For a description of m_value member, see System.IConvertible.ToDouble(System.IFormatProvider). + // + // Parameters: + // provider: + // m_value parameter is ignored. + // + // Returns: + // The value of the current instance, converted to a System.Double. + + double IConvertible.ToDouble( IFormatProvider provider ) + { + return Convert.ToDouble( m_value ); + } + + decimal IConvertible.ToDecimal( IFormatProvider provider ) + { + return Convert.ToDecimal( m_value ); + } + + DateTime IConvertible.ToDateTime( IFormatProvider provider ) + { + throw new InvalidCastException( $"InvalidCast_FromTo UInt64 DateTime" ); + } + + public object ToType( Type conversionType, IFormatProvider provider ) + { + return Convert.ChangeType( m_value, conversionType, provider ); + } + + #endregion + + } + + + + +} diff --git a/SharpLib.csproj b/SharpLib.csproj index c281455..4a2daad 100644 --- a/SharpLib.csproj +++ b/SharpLib.csproj @@ -23,6 +23,7 @@ + diff --git a/Token.cs b/Token.cs index 8a5a915..206ece6 100644 --- a/Token.cs +++ b/Token.cs @@ -1,54 +1,54 @@ -using System; -using System.Diagnostics; - -namespace lib -{ - - //TODO PERF fix this and make it fast. - - [Serializable] - public struct Token - { - public string str { get { return m_str; } } - - public Token( String str ) - { - m_str = str; - m_hash = m_str.GetHashCode(); - } - - public override bool Equals( object obj ) - { - if( !( obj is Token ) ) - return false; - - //This doesnt use as because Token is a struct - var otherId = (Token)obj; - - if( m_hash != otherId.m_hash ) - return false; - - return m_str == otherId.m_str; - } - - - public bool Equals_fast( Token other ) - { - return m_hash == other.m_hash && m_str == other.m_str; - } - - public override int GetHashCode() - { - return m_hash; - } - - public override string ToString() - { - return m_str; - } - - int m_hash; - String m_str; - } - -} +using System; +using System.Diagnostics; + +namespace lib +{ + + //TODO PERF fix this and make it fast. + + [Serializable] + public struct Token + { + public string str { get { return m_str; } } + + public Token( String str ) + { + m_str = str; + m_hash = m_str.GetHashCode(); + } + + public override bool Equals( object obj ) + { + if( !( obj is Token ) ) + return false; + + //This doesnt use as because Token is a struct + var otherId = (Token)obj; + + if( m_hash != otherId.m_hash ) + return false; + + return m_str == otherId.m_str; + } + + + public bool Equals_fast( Token other ) + { + return m_hash == other.m_hash && m_str == other.m_str; + } + + public override int GetHashCode() + { + return m_hash; + } + + public override string ToString() + { + return m_str; + } + + int m_hash; + String m_str; + } + +} diff --git a/Utilities.Interop.cs b/Utilities.Interop.cs index dab09bc..de5d43b 100644 --- a/Utilities.Interop.cs +++ b/Utilities.Interop.cs @@ -1,32 +1,32 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -// -// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +// +// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. #pragma warning disable SA1300 // Element must begin with upper-case letter #pragma warning disable SA1649 // File name must match first type name using System; using System.Runtime.CompilerServices; namespace lib -{ +{ /// /// Utility class. /// diff --git a/Utilities.cs b/Utilities.cs index 8604dba..bde0e72 100644 --- a/Utilities.cs +++ b/Utilities.cs @@ -22,6 +22,7 @@ // THE SOFTWARE. #pragma warning disable SA1405 // Debug.Assert must provide message text using att; + using System; using System.Collections; using System.Collections.Generic; @@ -88,12 +89,12 @@ namespace lib { if( !Directory.Exists( path ) ) { - lib.Log.info( $"Creating directory {path}" ); + log.info( $"Creating directory {path}" ); Directory.CreateDirectory( path ); } else { - lib.Log.debug( $"{path} already exists." ); + log.debug( $"{path} already exists." ); } } @@ -216,7 +217,7 @@ namespace lib unsafe { - fixed ( void* pBuffer = buffer ) + fixed( void* pBuffer = buffer ) Interop.Write( pBuffer, source, 0, source.Length ); } return buffer; @@ -339,7 +340,7 @@ namespace lib { unsafe { - fixed ( void* pDest = destination ) + fixed( void* pDest = destination ) { Write( (IntPtr)pDest, data, offset, count ); } diff --git a/att/CanBeNullAttribute.cs b/att/CanBeNullAttribute.cs index 6fe41c1..5bfe1a6 100644 --- a/att/CanBeNullAttribute.cs +++ b/att/CanBeNullAttribute.cs @@ -1,6 +1,6 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + /* MIT License Copyright (c) 2016 JetBrains http://www.jetbrains.com @@ -21,12 +21,12 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. */ - +SOFTWARE. */ + using System; namespace att -{ +{ /// /// Indicates that the value of the marked element could be null sometimes, so the check for null /// is necessary before its usage. @@ -45,7 +45,7 @@ namespace att AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter )] - public sealed class CanBeNullAttribute : Attribute + public sealed class CanBeNullAttribute: Attribute { } } diff --git a/att/NotNullAttribute.cs b/att/NotNullAttribute.cs index b0ca3b4..93d491b 100644 --- a/att/NotNullAttribute.cs +++ b/att/NotNullAttribute.cs @@ -1,10 +1,10 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + using System; namespace att -{ +{ /// /// Indicates that the value of the marked element could never be null. /// @@ -19,7 +19,7 @@ namespace att AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter )] - public sealed class NotNullAttribute : Attribute + public sealed class NotNullAttribute: Attribute { } } diff --git a/cfg/Config.cs b/cfg/Config.cs index 023ac19..250af20 100644 --- a/cfg/Config.cs +++ b/cfg/Config.cs @@ -6,7 +6,7 @@ using System.Reflection; namespace lib { - public class DescAttribute : Attribute + public class DescAttribute: Attribute { public string Desc { get; private set; } @@ -17,7 +17,7 @@ namespace lib } [Serializable] - public class ConfigCfg : Config + public class ConfigCfg: Config { public readonly bool writeOutTemplateFiles = true; } @@ -83,7 +83,7 @@ namespace lib try { - FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read ); + FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); XmlFormatter2 formatter = new XmlFormatter2(); @@ -93,13 +93,13 @@ namespace lib } catch( FileNotFoundException ) { - Type[] types = new Type[ 0 ]; - object[] parms = new object[ 0 ]; + Type[] types = new Type[0]; + object[] parms = new object[0]; //types[ 0 ] = typeof( string ); //parms[ 0 ] = filename; - ConstructorInfo cons = t?.GetConstructor( types ); + ConstructorInfo cons = t?.GetConstructor(types); try { @@ -107,7 +107,7 @@ namespace lib } catch( Exception e ) { - Log.error( $"Exception while creating config {t.ToString()}, Msg {e.Message}" ); + log.error( $"Exception while creating config {t.ToString()}, Msg {e.Message}" ); } //cfg.SetFilename( filename ); @@ -116,11 +116,11 @@ namespace lib { var templateFile = $"templates/{filename}"; - var dirName = Path.GetDirectoryName( templateFile ); + var dirName = Path.GetDirectoryName(templateFile); lib.Util.checkAndAddDirectory( dirName ); - lib.Log.info( $"Writing out template config of type {t?.Name} in {templateFile}" ); + log.info( $"Writing out template config of type {t?.Name} in {templateFile}" ); Config.save( cfg, templateFile ); } @@ -136,7 +136,7 @@ namespace lib static public void save( Config cfg, String filename ) { - FileStream fs = new FileStream( filename, FileMode.Create, FileAccess.Write ); + FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write); XmlFormatter2 formatter = new XmlFormatter2(); diff --git a/logging/Log.cs b/logging/Log.cs index 5ed06e6..72f06a5 100644 --- a/logging/Log.cs +++ b/logging/Log.cs @@ -8,66 +8,38 @@ using System.Collections.Immutable; using System.Reflection; //using System.Threading.Tasks; -namespace lib +static public class log { - - [Flags] - public enum LogTypeNew - { - Invalid = 0, - - // Frequency - FrequencyBase = 1, - FrequencyBits = 2, - FrequencyMask = ( ( 1 << FrequencyBits ) - 1 ) << FrequencyBase, - - Detail = 0b01 << FrequencyBase, - Normal = 0b10 << FrequencyBase, - Overview = 0b11 << FrequencyBase, - - // Type - TypeBase = FrequencyBase + FrequencyBits, - TypeBits = 3, - TypeMask = ( ( 1 << TypeBits ) - 1 ) << TypeBase, - - Startup = 0b001 << TypeBase, - Running = 0b010 << TypeBase, - Shutdown = 0b011 << TypeBase, - Error = 0b101 << TypeBase, - - } - - [Flags] public enum LogType { Invalid = 0, - Trace = 1, - Debug = 2, - Info = 3, - High = 4, - Warn = 5, - Error = 6, - Fatal = 7, + Trace = 1, + Debug = 2, + Info = 3, + High = 4, + Warn = 5, + Error = 6, + Fatal = 7, } public struct LogEvent { public DateTime Time; - public LogType LogType; - public string Msg; - public string Path; - public int Line; - public string Member; + public LogType LogType; + public string Msg; + public string Path; + public int Line; + public string Member; - public string Cat; - public object Obj; + public string Cat; + public object Obj; - static ImmutableDictionary m_shortname = ImmutableDictionary.Empty; + static ImmutableDictionary s_shortname = ImmutableDictionary.Empty; public LogEvent( LogType logType, string msg, string path, int line, string member, string cat, object obj ) @@ -76,17 +48,18 @@ namespace lib //Cache the automatic category names if( string.IsNullOrEmpty( cat ) ) { - if( m_shortname.TryGetValue( path, out var autoCat ) ) + var pathHash = path.GetHashCode(); + if( s_shortname.TryGetValue( pathHash, out var autoCat ) ) { cat = autoCat; } else { - var pathPieces = path.Split('\\'); + var pathPieces = path.Split( '\\' ); - var lastDir = pathPieces[pathPieces.Length - 2]; + var lastDir = pathPieces[ pathPieces.Length - 2 ]; - ImmutableInterlocked.AddOrUpdate( ref m_shortname, path, lastDir, ( key, value ) => { return lastDir; } ); + ImmutableInterlocked.AddOrUpdate( ref s_shortname, pathHash, lastDir, ( key, value ) => { return lastDir; } ); cat = lastDir; } @@ -107,343 +80,257 @@ namespace lib - public class Log : TraceListener + static public void create( string filename ) { - static public void create( string filename ) + createLog( filename ); + } + + + static public void destroy() + { + string msg = "==============================================================================\nLogfile shutdown at " + DateTime.Now.ToString(); + + var evt = CreateLogEvent( LogType.Info, msg, "System", null ); + + writeToAll( evt ); + + stop(); + } + + + static LogEvent CreateLogEvent( LogType logType, string msg, string cat, object obj, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) + { + var logEvent = new LogEvent( logType, msg, path, line, member, cat, obj ); + + return logEvent; + } + + + + + // Forwards. + static public void fatal( string msg, string cat = "", object obj = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) + { + logBase( msg, LogType.Fatal, path, line, member, cat, obj ); + } + + static public void error( string msg, string cat = "", object obj = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) + { + logBase( msg, LogType.Error, path, line, member, cat, obj ); + } + + static public void warn( string msg, string cat = "", object obj = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) + { + logBase( msg, LogType.Warn, path, line, member, cat, obj ); + } + + static public void info( string msg, string cat = "", object obj = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) + { + logBase( msg, LogType.Info, path, line, member, cat, obj ); + } + + static public void high( string msg, string cat = "", object obj = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) + { + logBase( msg, LogType.High, path, line, member, cat, obj ); + } + + static public void debug( string msg, string cat = "", object obj = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) + { + logBase( msg, LogType.Debug, path, line, member, cat, obj ); + } + + static public void trace( string msg, string cat = "", object obj = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) + { + logBase( msg, LogType.Trace, path, line, member, cat, obj ); + } + + static object s_lock = new object(); + + static public void logBase( string msg, LogType type = LogType.Debug, string path = "", int line = -1, string member = "", string cat = "unk", object obj = null ) + { + // @@@@@ TODO Get rid of this lock. + var evt = new LogEvent( type, msg, path, line, member, cat, obj ); + + lock( s_lock ) { - s_log = new Log( filename ); - } - - - static public void destroy() - { - string msg = "==============================================================================\nLogfile shutdown at " + DateTime.Now.ToString(); - - var evt = CreateLogEvent( LogType.Info, msg, "System", null ); - - s_log.writeToAll( evt ); - - s_log.stop(); - - s_log = null; - } - - static public Log s_log; - - /* - static public Log log - { - get - { - return s_log; - } - } - */ - - - static LogEvent CreateLogEvent( LogType logType, string msg, string cat, object obj, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) - { - var logEvent = new LogEvent( logType, msg, path, line, member, cat, obj ); - - return logEvent; - } - - - - - // Forwards. - static public void fatal( string msg, string cat = "", object obj = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) - { - log( msg, LogType.Fatal, path, line, member, cat, obj ); - } - - static public void error( string msg, string cat = "", object obj = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) - { - log( msg, LogType.Error, path, line, member, cat, obj ); - } - - static public void warn( string msg, string cat = "", object obj = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) - { - log( msg, LogType.Warn, path, line, member, cat, obj ); - } - - static public void info( string msg, string cat = "", object obj = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) - { - log( msg, LogType.Info, path, line, member, cat, obj ); - } - - static public void high( string msg, string cat = "", object obj = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) - { - log( msg, LogType.High, path, line, member, cat, obj ); - } - - static public void debug( string msg, string cat = "", object obj = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) - { - log( msg, LogType.Debug, path, line, member, cat, obj ); - } - - static public void trace( string msg, string cat = "", object obj = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) - { - log( msg, LogType.Trace, path, line, member, cat, obj ); - } - - static public void log( string msg, LogType type = LogType.Debug, string path = "", int line = -1, string member = "", string cat = "unk", object obj = null ) - { - // @@@@@ TODO Get rid of this lock. - var evt = new LogEvent( type, msg, path, line, member, cat, obj ); - - lock( s_log ) - { - s_log.writeToAll( evt ); - } - } - - static public void logProps( object obj, string header, LogType type = LogType.Debug, string cat = "", string prefix = "" ) - { - var list = scr.GetAllProperties( obj.GetType() ); - - lock( s_log ) - { - var evt = CreateLogEvent( type, header, cat, obj ); - - s_log.writeToAll( evt ); - - foreach( var pi in list ) - { - try - { - var v = pi.GetValue( obj ); - - log( $"{prefix}{pi.Name} = {v}", type, cat ); - } - catch( Exception ex ) - { - log( $"Exception processing {pi.Name} {ex.Message}", LogType.Error, "log" ); - } - } - - } - } - - //This might seem a little odd, but the intent is that usually you wont need to set notExpectedValue. - static public void expected( T value, string falseString, string trueString = "", T notExpectedValue = default( T ) ) - { - - if( !value.Equals( notExpectedValue ) ) - { - lib.Log.info( $"Properly got {value}{trueString}" ); - } - else - { - lib.Log.warn( $"Got {notExpectedValue} instead of {value}{falseString}" ); - } - } - - - private Log( string filename ) - { - //TODO: Fix this so itll work without a directory. - Directory.CreateDirectory( Path.GetDirectoryName( filename ) ); - - m_stream = new FileStream( filename, FileMode.Append, FileAccess.Write ); - m_writer = new StreamWriter( m_stream ); - - m_errorStream = new FileStream( filename + ".error", FileMode.Append, FileAccess.Write ); - m_errorWriter = new StreamWriter( m_errorStream ); - - //Debug.Listeners.Add( this ); - - string msg = "\n==============================================================================\nLogfile " + filename + " startup at " + DateTime.Now.ToString(); - - var evt = CreateLogEvent( LogType.Info, msg, "System", null ); - writeToAll( evt ); } - - public override void Write( string msg ) - { - WriteLine( msg ); - } - - public override void WriteLine( string msg ) - { - error( msg ); - //base.WriteLine( msg ); - } - - void stop() - { - m_writer.Close(); - m_stream.Close(); - - m_errorWriter.Close(); - m_errorStream.Close(); - } - - public void addDelegate( Log_delegate cb ) - { - m_delegates.Add( cb ); - } - - /* - private void writeFileAndLine( StackTrace st ) - { - StackFrame frame = st.GetFrame( 1 ); - - string srcFile = frame.GetFileName(); - string srcLine = frame.GetFileLineNumber().Tostring(); - - Console.WriteLine( $"{srcFile} ({srcLine}):" ); - } - - private void writeStack( StackTrace st ) - { - for( int i=0; i { - StackTrace st = new StackTrace( true ); - - writeStack( st ); - - string msgPrint = msg; - - if( args.Length > 0 ) - { - msgPrint = string.Format( msg, args ); - } - - writeToAll( "error", "log", msgPrint ); - //} ); - } - private void warn_i( string msg, object obj ) - { - //var t = Task.Run( () => { - StackTrace st = new StackTrace( true ); - - writeStack( st ); - - string msgPrint = msg; - - if( args.Length > 0 ) - { - msgPrint = string.Format( msg, args ); - } - - writeToAll( "warn", "log", msgPrint ); - //}); - } - private void info_i( string msg, object obj ) - { - //var t = Task.Run( () => { - StackTrace st = new StackTrace( true ); - - string msgPrint = msg; - - if( args.Length > 0 ) - { - msgPrint = string.Format( msg, args ); - } - - writeToAll( "info", "log", msgPrint ); - //} ); - } - */ - - private Stream m_stream; - private StreamWriter m_writer; - - private Stream m_errorStream; - private StreamWriter m_errorWriter; - - private ArrayList m_delegates = new ArrayList(); } + static public void logProps( object obj, string header, LogType type = LogType.Debug, string cat = "", string prefix = "", [CallerFilePath] string path = "", [CallerLineNumber] int line = -1, [CallerMemberName] string member = "" ) + { + var list = refl.GetAllProperties( obj.GetType() ); + + lock( s_lock ) + { + var evt = new LogEvent( type, header, path, line, member, cat, obj ); + //var evt = CreateLogEvent( type, header, cat, obj ); + + writeToAll( evt ); + + foreach( var pi in list ) + { + try + { + var v = pi.GetValue( obj ); + + logBase( $"{prefix}{pi.Name} = {v}", type, path, line, member, cat ); + } + catch( Exception ex ) + { + logBase( $"Exception processing {pi.Name} {ex.Message}", LogType.Error, "log" ); + } + } + + } + } + + //This might seem a little odd, but the intent is that usually you wont need to set notExpectedValue. + static public void expected( T value, string falseString, string trueString = "", T notExpectedValue = default( T ) ) + { + + if( !value.Equals( notExpectedValue ) ) + { + log.info( $"Properly got {value}{trueString}" ); + } + else + { + log.warn( $"Got {notExpectedValue} instead of {value}{falseString}" ); + } + } + + + static private void createLog( string filename ) + { + + string dir = Path.GetDirectoryName( filename ); + + if( dir.Length > 0 ) + { + Directory.CreateDirectory( dir ); + } + + s_stream = new FileStream( filename, FileMode.Append, FileAccess.Write ); + s_writer = new StreamWriter( s_stream ); + + s_errorStream = new FileStream( filename + ".error", FileMode.Append, FileAccess.Write ); + s_errorWriter = new StreamWriter( s_errorStream ); + + //Debug.Listeners.Add( this ); + + string msg = "\n==============================================================================\nLogfile " + filename + " startup at " + DateTime.Now.ToString(); + + var evt = CreateLogEvent( LogType.Info, msg, "System", null ); + + writeToAll( evt ); + } + + /* +static public override void Write( string msg ) { + WriteLine( msg ); + } + +static public override void WriteLine( string msg ) { + error( msg ); + //base.WriteLine( msg ); + } + */ + + static void stop() + { + s_writer.Close(); + s_stream.Close(); + + s_errorWriter.Close(); + s_errorStream.Close(); + } + + static public void addDelegate( Log_delegate cb ) + { + s_delegates.Add( cb ); + } + + public static char getSymbol( LogType type ) + { + switch( type ) + { + case LogType.Trace: + return ' '; + case LogType.Debug: + return ' '; + case LogType.Info: + return ' '; + case LogType.High: + return '+'; + case LogType.Warn: + return '+'; + case LogType.Error: + return '*'; + case LogType.Fatal: + return '*'; + default: + return '?'; + } + } + + static private void writeToAll( LogEvent evt ) + { + try + { + // _SHOULDNT_ need this since we lock at the top. + //lock( this ) + { + char sym = getSymbol( evt.LogType ); + + var truncatedCat = evt.Cat.Substring( 0, Math.Min( 8, evt.Cat.Length ) ); + + string finalLine = string.Format( "{0,-8}{1}| {2}", truncatedCat, sym, evt.Msg ); + + //Console.WriteLine( finalMsg ); + //Console.Out.Write( finalMsg ); + + s_writer.WriteLine( finalLine ); + + Console.WriteLine( finalLine ); + + Debug.WriteLine( finalLine ); + + s_writer.Flush(); + + foreach( Log_delegate cb in s_delegates ) + { + { + cb( evt ); + } + } + } + } + catch( Exception ex ) + { + Console.WriteLine( "EXCEPTION DURING LOGGING" ); + Console.WriteLine( "EXCEPTION DURING LOGGING" ); + Console.WriteLine( "EXCEPTION DURING LOGGING" ); + Console.WriteLine( "EXCEPTION DURING LOGGING" ); + Console.WriteLine( "EXCEPTION DURING LOGGING" ); + Console.WriteLine( $"Exception {ex}" ); + + Debug.WriteLine( "EXCEPTION DURING LOGGING" ); + Debug.WriteLine( "EXCEPTION DURING LOGGING" ); + Debug.WriteLine( "EXCEPTION DURING LOGGING" ); + Debug.WriteLine( "EXCEPTION DURING LOGGING" ); + Debug.WriteLine( "EXCEPTION DURING LOGGING" ); + Debug.WriteLine( $"Exception {ex}" ); + } + } + + private static Stream s_stream; + private static StreamWriter s_writer; + + private static Stream s_errorStream; + private static StreamWriter s_errorWriter; + + private static ArrayList s_delegates = new ArrayList(); + diff --git a/math/AngleSingle.cs b/math/AngleSingle.cs index 225d9d9..08a7d90 100644 --- a/math/AngleSingle.cs +++ b/math/AngleSingle.cs @@ -1,10 +1,10 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -// -// ----------------------------------------------------------------------------- -// Original code from SlimMath project. http://code.google.com/p/slimmath/ -// Greetings to SlimDX Group. Original code published with the following license: -// ----------------------------------------------------------------------------- +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +// +// ----------------------------------------------------------------------------- +// Original code from SlimMath project. http://code.google.com/p/slimmath/ +// Greetings to SlimDX Group. Original code published with the following license: +// ----------------------------------------------------------------------------- /* * Copyright (c) 2007-2011 SlimDX Group * @@ -25,755 +25,755 @@ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. -*/ +*/ using System; using System.Globalization; using System.Runtime.Serialization; namespace math -{ - /// - /// Represents a unit independant angle using a single-precision floating-point - /// internal representation. - /// - [DataStyle(DataStyle.Compact)] - [DataContract] - public struct AngleSingle : IComparable, IComparable, IEquatable, IFormattable - { - /// - /// A value that specifies the size of a single degree. - /// - public const float Degree = 0.002777777777777778f; - - /// - /// A value that specifies the size of a single minute. - /// - public const float Minute = 0.000046296296296296f; - - /// - /// A value that specifies the size of a single second. - /// - public const float Second = 0.000000771604938272f; - - /// - /// A value that specifies the size of a single radian. - /// - public const float Radian = 0.159154943091895336f; - - /// - /// A value that specifies the size of a single milliradian. - /// - public const float Milliradian = 0.0001591549431f; - - /// - /// A value that specifies the size of a single gradian. - /// - public const float Gradian = 0.0025f; - - /// - /// The internal representation of the angle. - /// - private float radians; - - /// - /// Initializes a new instance of the struct with the - /// given unit dependant angle and unit type. - /// - /// A unit dependant measure of the angle. - /// The type of unit the angle argument is. - public AngleSingle(float angle, AngleType type) - { - switch (type) - { - case AngleType.Revolution: - radians = MathUtil.RevolutionsToRadians(angle); - break; - - case AngleType.Degree: - radians = MathUtil.DegreesToRadians(angle); - break; - - case AngleType.Radian: - radians = angle; - break; - - case AngleType.Gradian: - radians = MathUtil.GradiansToRadians(angle); - break; - - default: - radians = 0.0f; - break; - } - } - - /// - /// Initializes a new instance of the struct using the - /// arc length formula (θ = s/r). - /// - /// The measure of the arc. - /// The radius of the circle. - public AngleSingle(float arcLength, float radius) - { - radians = arcLength / radius; - } - - /// - /// Wraps this math.AngleSingle to be in the range [π, -π]. - /// - public void Wrap() - { - float newangle = (float)Math.IEEERemainder(radians, MathUtil.TwoPi); - - if (newangle <= -MathUtil.Pi) - newangle += MathUtil.TwoPi; - else if (newangle > MathUtil.Pi) - newangle -= MathUtil.TwoPi; - - radians = newangle; - } - - /// - /// Wraps this math.AngleSingle to be in the range [0, 2π). - /// - public void WrapPositive() - { - float newangle = radians % MathUtil.TwoPi; - - if (newangle < 0.0) - newangle += MathUtil.TwoPi; - - radians = newangle; - } - - /// - /// Gets or sets the total number of revolutions this math.AngleSingle represents. - /// - [DataMemberIgnore] - public float Revolutions - { - get { return MathUtil.RadiansToRevolutions(radians); } - set { radians = MathUtil.RevolutionsToRadians(value); } - } - - /// - /// Gets or sets the total number of degrees this math.AngleSingle represents. - /// - [DataMemberIgnore] - public float Degrees - { - get { return MathUtil.RadiansToDegrees(radians); } - set { radians = MathUtil.DegreesToRadians(value); } - } - - /// - /// Gets or sets the minutes component of the degrees this math.AngleSingle represents. - /// When setting the minutes, if the value is in the range (-60, 60) the whole degrees are - /// not changed; otherwise, the whole degrees may be changed. Fractional values may set - /// the seconds component. - /// - [DataMemberIgnore] - public float Minutes - { - get - { - float degrees = MathUtil.RadiansToDegrees(radians); - - if (degrees < 0) - { - float degreesfloor = (float)Math.Ceiling(degrees); - return (degrees - degreesfloor) * 60.0f; - } - else - { - float degreesfloor = (float)Math.Floor(degrees); - return (degrees - degreesfloor) * 60.0f; - } - } - set - { - float degrees = MathUtil.RadiansToDegrees(radians); - float degreesfloor = (float)Math.Floor(degrees); - - degreesfloor += value / 60.0f; - radians = MathUtil.DegreesToRadians(degreesfloor); - } - } - - /// - /// Gets or sets the seconds of the degrees this math.AngleSingle represents. - /// When setting te seconds, if the value is in the range (-60, 60) the whole minutes - /// or whole degrees are not changed; otherwise, the whole minutes or whole degrees - /// may be changed. - /// - [DataMemberIgnore] - public float Seconds - { - get - { - float degrees = MathUtil.RadiansToDegrees(radians); - - if (degrees < 0) - { - float degreesfloor = (float)Math.Ceiling(degrees); - - float minutes = (degrees - degreesfloor) * 60.0f; - float minutesfloor = (float)Math.Ceiling(minutes); - - return (minutes - minutesfloor) * 60.0f; - } - else - { - float degreesfloor = (float)Math.Floor(degrees); - - float minutes = (degrees - degreesfloor) * 60.0f; - float minutesfloor = (float)Math.Floor(minutes); - - return (minutes - minutesfloor) * 60.0f; - } - } - set - { - float degrees = MathUtil.RadiansToDegrees(radians); - float degreesfloor = (float)Math.Floor(degrees); - - float minutes = (degrees - degreesfloor) * 60.0f; - float minutesfloor = (float)Math.Floor(minutes); - - minutesfloor += value / 60.0f; - degreesfloor += minutesfloor / 60.0f; - radians = MathUtil.DegreesToRadians(degreesfloor); - } - } - - /// - /// Gets or sets the total number of radians this math.AngleSingle represents. - /// - public float Radians - { - get { return radians; } - set { radians = value; } - } - - /// - /// Gets or sets the total number of milliradians this math.AngleSingle represents. - /// One milliradian is equal to 1/(2000π). - /// - [DataMemberIgnore] - public float Milliradians - { - get { return radians / (Milliradian * MathUtil.TwoPi); } - set { radians = value * (Milliradian * MathUtil.TwoPi); } - } - - /// - /// Gets or sets the total number of gradians this math.AngleSingle represents. - /// - [DataMemberIgnore] - public float Gradians - { - get { return MathUtil.RadiansToGradians(radians); } - set { radians = MathUtil.GradiansToRadians(value); } - } - - /// - /// Gets a System.Boolean that determines whether this math.Angle - /// is a right angle (i.e. 90° or π/2). - /// - [DataMemberIgnore] - public bool IsRight - { - get { return radians == MathUtil.PiOverTwo; } - } - - /// - /// Gets a System.Boolean that determines whether this math.Angle - /// is a straight angle (i.e. 180° or π). - /// - [DataMemberIgnore] - public bool IsStraight - { - get { return radians == MathUtil.Pi; } - } - - /// - /// Gets a System.Boolean that determines whether this math.Angle - /// is a full rotation angle (i.e. 360° or 2π). - /// - [DataMemberIgnore] - public bool IsFullRotation - { - get { return radians == MathUtil.TwoPi; } - } - - /// - /// Gets a System.Boolean that determines whether this math.Angle - /// is an oblique angle (i.e. is not 90° or a multiple of 90°). - /// - [DataMemberIgnore] - public bool IsOblique - { - get { return WrapPositive(this).radians != MathUtil.PiOverTwo; } - } - - /// - /// Gets a System.Boolean that determines whether this math.Angle - /// is an acute angle (i.e. less than 90° but greater than 0°). - /// - [DataMemberIgnore] - public bool IsAcute - { - get { return radians > 0.0 && radians < MathUtil.PiOverTwo; } - } - - /// - /// Gets a System.Boolean that determines whether this math.Angle - /// is an obtuse angle (i.e. greater than 90° but less than 180°). - /// - [DataMemberIgnore] - public bool IsObtuse - { - get { return radians > MathUtil.PiOverTwo && radians < MathUtil.Pi; } - } - - /// - /// Gets a System.Boolean that determines whether this math.Angle - /// is a reflex angle (i.e. greater than 180° but less than 360°). - /// - [DataMemberIgnore] - public bool IsReflex - { - get { return radians > MathUtil.Pi && radians < MathUtil.TwoPi; } - } - - /// - /// Gets a math.AngleSingle instance that complements this angle (i.e. the two angles add to 90°). - /// - [DataMemberIgnore] - public AngleSingle Complement - { - get { return new AngleSingle(MathUtil.PiOverTwo - radians, AngleType.Radian); } - } - - /// - /// Gets a math.AngleSingle instance that supplements this angle (i.e. the two angles add to 180°). - /// - [DataMemberIgnore] - public AngleSingle Supplement - { - get { return new AngleSingle(MathUtil.Pi - radians, AngleType.Radian); } - } - - /// - /// Wraps the math.AngleSingle given in the value argument to be in the range [π, -π]. - /// - /// A math.AngleSingle to wrap. - /// The math.AngleSingle that is wrapped. - public static AngleSingle Wrap(AngleSingle value) - { - value.Wrap(); - return value; - } - - /// - /// Wraps the math.AngleSingle given in the value argument to be in the range [0, 2π). - /// - /// A math.AngleSingle to wrap. - /// The math.AngleSingle that is wrapped. - public static AngleSingle WrapPositive(AngleSingle value) - { - value.WrapPositive(); - return value; - } - - /// - /// Compares two math.AngleSingle instances and returns the smaller angle. - /// - /// The first math.AngleSingle instance to compare. - /// The second math.AngleSingle instance to compare. - /// The smaller of the two given math.AngleSingle instances. - public static AngleSingle Min(AngleSingle left, AngleSingle right) - { - if (left.radians < right.radians) - return left; - - return right; - } - - /// - /// Compares two math.AngleSingle instances and returns the greater angle. - /// - /// The first math.AngleSingle instance to compare. - /// The second math.AngleSingle instance to compare. - /// The greater of the two given math.AngleSingle instances. - public static AngleSingle Max(AngleSingle left, AngleSingle right) - { - if (left.radians > right.radians) - return left; - - return right; - } - - /// - /// Adds two math.AngleSingle objects and returns the result. - /// - /// The first object to add. - /// The second object to add. - /// The value of the two objects added together. - public static AngleSingle Add(AngleSingle left, AngleSingle right) - { - return new AngleSingle(left.radians + right.radians, AngleType.Radian); - } - - /// - /// Subtracts two math.AngleSingle objects and returns the result. - /// - /// The first object to subtract. - /// The second object to subtract. - /// The value of the two objects subtracted. - public static AngleSingle Subtract(AngleSingle left, AngleSingle right) - { - return new AngleSingle(left.radians - right.radians, AngleType.Radian); - } - - /// - /// Multiplies two math.AngleSingle objects and returns the result. - /// - /// The first object to multiply. - /// The second object to multiply. - /// The value of the two objects multiplied together. - public static AngleSingle Multiply(AngleSingle left, AngleSingle right) - { - return new AngleSingle(left.radians * right.radians, AngleType.Radian); - } - - /// - /// Divides two math.AngleSingle objects and returns the result. - /// - /// The numerator object. - /// The denominator object. - /// The value of the two objects divided. - public static AngleSingle Divide(AngleSingle left, AngleSingle right) - { - return new AngleSingle(left.radians / right.radians, AngleType.Radian); - } - - /// - /// Gets a new math.AngleSingle instance that represents the zero angle (i.e. 0°). - /// - public static AngleSingle ZeroAngle - { - get { return new AngleSingle(0.0f, AngleType.Radian); } - } - - /// - /// Gets a new math.AngleSingle instance that represents the right angle (i.e. 90° or π/2). - /// - public static AngleSingle RightAngle - { - get { return new AngleSingle(MathUtil.PiOverTwo, AngleType.Radian); } - } - - /// - /// Gets a new math.AngleSingle instance that represents the straight angle (i.e. 180° or π). - /// - public static AngleSingle StraightAngle - { - get { return new AngleSingle(MathUtil.Pi, AngleType.Radian); } - } - - /// - /// Gets a new math.AngleSingle instance that represents the full rotation angle (i.e. 360° or 2π). - /// - public static AngleSingle FullRotationAngle - { - get { return new AngleSingle(MathUtil.TwoPi, AngleType.Radian); } - } - - /// - /// Returns a System.Boolean that indicates whether the values of two math.Angle - /// objects are equal. - /// - /// The first object to compare. - /// The second object to compare. - /// True if the left and right parameters have the same value; otherwise, false. - public static bool operator ==(AngleSingle left, AngleSingle right) - { - return left.radians == right.radians; - } - - /// - /// Returns a System.Boolean that indicates whether the values of two math.Angle - /// objects are not equal. - /// - /// The first object to compare. - /// The second object to compare. - /// True if the left and right parameters do not have the same value; otherwise, false. - public static bool operator !=(AngleSingle left, AngleSingle right) - { - return left.radians != right.radians; - } - - /// - /// Returns a System.Boolean that indicates whether a math.Angle - /// object is less than another math.AngleSingle object. - /// - /// The first object to compare. - /// The second object to compare. - /// True if left is less than right; otherwise, false. - public static bool operator <(AngleSingle left, AngleSingle right) - { - return left.radians < right.radians; - } - - /// - /// Returns a System.Boolean that indicates whether a math.Angle - /// object is greater than another math.AngleSingle object. - /// - /// The first object to compare. - /// The second object to compare. - /// True if left is greater than right; otherwise, false. - public static bool operator >(AngleSingle left, AngleSingle right) - { - return left.radians > right.radians; - } - - /// - /// Returns a System.Boolean that indicates whether a math.Angle - /// object is less than or equal to another math.AngleSingle object. - /// - /// The first object to compare. - /// The second object to compare. - /// True if left is less than or equal to right; otherwise, false. - public static bool operator <=(AngleSingle left, AngleSingle right) - { - return left.radians <= right.radians; - } - - /// - /// Returns a System.Boolean that indicates whether a math.Angle - /// object is greater than or equal to another math.AngleSingle object. - /// - /// The first object to compare. - /// The second object to compare. - /// True if left is greater than or equal to right; otherwise, false. - public static bool operator >=(AngleSingle left, AngleSingle right) - { - return left.radians >= right.radians; - } - - /// - /// Returns the value of the math.AngleSingle operand. (The sign of - /// the operand is unchanged.) - /// - /// A math.AngleSingle object. - /// The value of the value parameter. - public static AngleSingle operator +(AngleSingle value) - { - return value; - } - - /// - /// Returns the the negated value of the math.AngleSingle operand. - /// - /// A math.AngleSingle object. - /// The negated value of the value parameter. - public static AngleSingle operator -(AngleSingle value) - { - return new AngleSingle(-value.radians, AngleType.Radian); - } - - /// - /// Adds two math.AngleSingle objects and returns the result. - /// - /// The first object to add. - /// The second object to add. - /// The value of the two objects added together. - public static AngleSingle operator +(AngleSingle left, AngleSingle right) - { - return new AngleSingle(left.radians + right.radians, AngleType.Radian); - } - - /// - /// Subtracts two math.AngleSingle objects and returns the result. - /// - /// The first object to subtract - /// The second object to subtract. - /// The value of the two objects subtracted. - public static AngleSingle operator -(AngleSingle left, AngleSingle right) - { - return new AngleSingle(left.radians - right.radians, AngleType.Radian); - } - - /// - /// Multiplies two math.AngleSingle objects and returns the result. - /// - /// The first object to multiply. - /// The second object to multiply. - /// The value of the two objects multiplied together. - public static AngleSingle operator *(AngleSingle left, AngleSingle right) - { - return new AngleSingle(left.radians * right.radians, AngleType.Radian); - } - - /// - /// Divides two math.AngleSingle objects and returns the result. - /// - /// The numerator object. - /// The denominator object. - /// The value of the two objects divided. - public static AngleSingle operator /(AngleSingle left, AngleSingle right) - { - return new AngleSingle(left.radians / right.radians, AngleType.Radian); - } - - /// - /// Compares this instance to a specified object and returns an integer that - /// indicates whether the value of this instance is less than, equal to, or greater - /// than the value of the specified object. - /// - /// The object to compare. - /// - /// A signed integer that indicates the relationship of the current instance - /// to the obj parameter. If the value is less than zero, the current instance - /// is less than the other. If the value is zero, the current instance is equal - /// to the other. If the value is greater than zero, the current instance is - /// greater than the other. - /// - public int CompareTo(object other) - { - if (other == null) - return 1; - - if (!(other is AngleSingle)) - throw new ArgumentException("Argument must be of type Angle.", "other"); - - float radians = ((AngleSingle)other).radians; - - if (this.radians > radians) - return 1; - - if (this.radians < radians) - return -1; - - return 0; - } - - /// - /// Compares this instance to a second math.AngleSingle and returns - /// an integer that indicates whether the value of this instance is less than, - /// equal to, or greater than the value of the specified object. - /// - /// The object to compare. - /// - /// A signed integer that indicates the relationship of the current instance - /// to the obj parameter. If the value is less than zero, the current instance - /// is less than the other. If the value is zero, the current instance is equal - /// to the other. If the value is greater than zero, the current instance is - /// greater than the other. - /// - public int CompareTo(AngleSingle other) - { - if (this.radians > other.radians) - return 1; - - if (this.radians < other.radians) - return -1; - - return 0; - } - - /// - /// Returns a value that indicates whether the current instance and a specified - /// math.AngleSingle object have the same value. - /// - /// The object to compare. - /// - /// Returns true if this math.AngleSingle object and another have the same value; - /// otherwise, false. - /// - public bool Equals(AngleSingle other) - { - return this == other; - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override string ToString() - { - return string.Format(CultureInfo.CurrentCulture, MathUtil.RadiansToDegrees(radians).ToString("0.##°")); - } - - /// - /// Returns a that represents this instance. - /// - /// The format. - /// - /// A that represents this instance. - /// - public string ToString(string format) - { - if (format == null) - return ToString(); - - return string.Format(CultureInfo.CurrentCulture, $"{MathUtil.RadiansToDegrees(radians).ToString(format, CultureInfo.CurrentCulture)}°" ); - } - - /// - /// Returns a that represents this instance. - /// - /// The format provider. - /// - /// A that represents this instance. - /// - public string ToString(IFormatProvider formatProvider) - { - return string.Format(formatProvider, MathUtil.RadiansToDegrees(radians).ToString("0.##°")); - } - - /// - /// Returns a that represents this instance. - /// - /// The format. - /// The format provider. - /// - /// A that represents this instance. - /// - public string ToString(string format, IFormatProvider formatProvider) - { - if (format == null) - return ToString(formatProvider); - - return string.Format(formatProvider, "{0}°", MathUtil.RadiansToDegrees(radians).ToString(format, CultureInfo.CurrentCulture)); - } - - /// - /// Returns a hash code for this math.AngleSingle instance. - /// - /// A 32-bit signed integer hash code. - public override int GetHashCode() - { - return (int)(BitConverter.DoubleToInt64Bits(radians) % int.MaxValue); - } - - /// - /// Returns a value that indicates whether the current instance and a specified - /// object have the same value. - /// - /// The object to compare. - /// - /// Returns true if the obj parameter is a math.AngleSingle object or a type - /// capable of implicit conversion to a math.AngleSingle value, and - /// its value is equal to the value of the current math.Angle - /// object; otherwise, false. - /// - public override bool Equals(object obj) - { - return (obj is AngleSingle) && (this == (AngleSingle)obj); - } - } +{ + /// + /// Represents a unit independant angle using a single-precision floating-point + /// internal representation. + /// + [DataStyle( DataStyle.Compact )] + [DataContract] + public struct AngleSingle: IComparable, IComparable, IEquatable, IFormattable + { + /// + /// A value that specifies the size of a single degree. + /// + public const float Degree = 0.002777777777777778f; + + /// + /// A value that specifies the size of a single minute. + /// + public const float Minute = 0.000046296296296296f; + + /// + /// A value that specifies the size of a single second. + /// + public const float Second = 0.000000771604938272f; + + /// + /// A value that specifies the size of a single radian. + /// + public const float Radian = 0.159154943091895336f; + + /// + /// A value that specifies the size of a single milliradian. + /// + public const float Milliradian = 0.0001591549431f; + + /// + /// A value that specifies the size of a single gradian. + /// + public const float Gradian = 0.0025f; + + /// + /// The internal representation of the angle. + /// + private float radians; + + /// + /// Initializes a new instance of the struct with the + /// given unit dependant angle and unit type. + /// + /// A unit dependant measure of the angle. + /// The type of unit the angle argument is. + public AngleSingle( float angle, AngleType type ) + { + switch( type ) + { + case AngleType.Revolution: + radians = MathUtil.RevolutionsToRadians( angle ); + break; + + case AngleType.Degree: + radians = MathUtil.DegreesToRadians( angle ); + break; + + case AngleType.Radian: + radians = angle; + break; + + case AngleType.Gradian: + radians = MathUtil.GradiansToRadians( angle ); + break; + + default: + radians = 0.0f; + break; + } + } + + /// + /// Initializes a new instance of the struct using the + /// arc length formula (θ = s/r). + /// + /// The measure of the arc. + /// The radius of the circle. + public AngleSingle( float arcLength, float radius ) + { + radians = arcLength / radius; + } + + /// + /// Wraps this math.AngleSingle to be in the range [π, -π]. + /// + public void Wrap() + { + float newangle = (float)Math.IEEERemainder(radians, MathUtil.TwoPi); + + if( newangle <= -MathUtil.Pi ) + newangle += MathUtil.TwoPi; + else if( newangle > MathUtil.Pi ) + newangle -= MathUtil.TwoPi; + + radians = newangle; + } + + /// + /// Wraps this math.AngleSingle to be in the range [0, 2π). + /// + public void WrapPositive() + { + float newangle = radians % MathUtil.TwoPi; + + if( newangle < 0.0 ) + newangle += MathUtil.TwoPi; + + radians = newangle; + } + + /// + /// Gets or sets the total number of revolutions this math.AngleSingle represents. + /// + [DataMemberIgnore] + public float Revolutions + { + get { return MathUtil.RadiansToRevolutions( radians ); } + set { radians = MathUtil.RevolutionsToRadians( value ); } + } + + /// + /// Gets or sets the total number of degrees this math.AngleSingle represents. + /// + [DataMemberIgnore] + public float Degrees + { + get { return MathUtil.RadiansToDegrees( radians ); } + set { radians = MathUtil.DegreesToRadians( value ); } + } + + /// + /// Gets or sets the minutes component of the degrees this math.AngleSingle represents. + /// When setting the minutes, if the value is in the range (-60, 60) the whole degrees are + /// not changed; otherwise, the whole degrees may be changed. Fractional values may set + /// the seconds component. + /// + [DataMemberIgnore] + public float Minutes + { + get + { + float degrees = MathUtil.RadiansToDegrees(radians); + + if( degrees < 0 ) + { + float degreesfloor = (float)Math.Ceiling(degrees); + return ( degrees - degreesfloor ) * 60.0f; + } + else + { + float degreesfloor = (float)Math.Floor(degrees); + return ( degrees - degreesfloor ) * 60.0f; + } + } + set + { + float degrees = MathUtil.RadiansToDegrees(radians); + float degreesfloor = (float)Math.Floor(degrees); + + degreesfloor += value / 60.0f; + radians = MathUtil.DegreesToRadians( degreesfloor ); + } + } + + /// + /// Gets or sets the seconds of the degrees this math.AngleSingle represents. + /// When setting te seconds, if the value is in the range (-60, 60) the whole minutes + /// or whole degrees are not changed; otherwise, the whole minutes or whole degrees + /// may be changed. + /// + [DataMemberIgnore] + public float Seconds + { + get + { + float degrees = MathUtil.RadiansToDegrees(radians); + + if( degrees < 0 ) + { + float degreesfloor = (float)Math.Ceiling(degrees); + + float minutes = (degrees - degreesfloor) * 60.0f; + float minutesfloor = (float)Math.Ceiling(minutes); + + return ( minutes - minutesfloor ) * 60.0f; + } + else + { + float degreesfloor = (float)Math.Floor(degrees); + + float minutes = (degrees - degreesfloor) * 60.0f; + float minutesfloor = (float)Math.Floor(minutes); + + return ( minutes - minutesfloor ) * 60.0f; + } + } + set + { + float degrees = MathUtil.RadiansToDegrees(radians); + float degreesfloor = (float)Math.Floor(degrees); + + float minutes = (degrees - degreesfloor) * 60.0f; + float minutesfloor = (float)Math.Floor(minutes); + + minutesfloor += value / 60.0f; + degreesfloor += minutesfloor / 60.0f; + radians = MathUtil.DegreesToRadians( degreesfloor ); + } + } + + /// + /// Gets or sets the total number of radians this math.AngleSingle represents. + /// + public float Radians + { + get { return radians; } + set { radians = value; } + } + + /// + /// Gets or sets the total number of milliradians this math.AngleSingle represents. + /// One milliradian is equal to 1/(2000π). + /// + [DataMemberIgnore] + public float Milliradians + { + get { return radians / ( Milliradian * MathUtil.TwoPi ); } + set { radians = value * ( Milliradian * MathUtil.TwoPi ); } + } + + /// + /// Gets or sets the total number of gradians this math.AngleSingle represents. + /// + [DataMemberIgnore] + public float Gradians + { + get { return MathUtil.RadiansToGradians( radians ); } + set { radians = MathUtil.GradiansToRadians( value ); } + } + + /// + /// Gets a System.Boolean that determines whether this math.Angle + /// is a right angle (i.e. 90° or π/2). + /// + [DataMemberIgnore] + public bool IsRight + { + get { return radians == MathUtil.PiOverTwo; } + } + + /// + /// Gets a System.Boolean that determines whether this math.Angle + /// is a straight angle (i.e. 180° or π). + /// + [DataMemberIgnore] + public bool IsStraight + { + get { return radians == MathUtil.Pi; } + } + + /// + /// Gets a System.Boolean that determines whether this math.Angle + /// is a full rotation angle (i.e. 360° or 2π). + /// + [DataMemberIgnore] + public bool IsFullRotation + { + get { return radians == MathUtil.TwoPi; } + } + + /// + /// Gets a System.Boolean that determines whether this math.Angle + /// is an oblique angle (i.e. is not 90° or a multiple of 90°). + /// + [DataMemberIgnore] + public bool IsOblique + { + get { return WrapPositive( this ).radians != MathUtil.PiOverTwo; } + } + + /// + /// Gets a System.Boolean that determines whether this math.Angle + /// is an acute angle (i.e. less than 90° but greater than 0°). + /// + [DataMemberIgnore] + public bool IsAcute + { + get { return radians > 0.0 && radians < MathUtil.PiOverTwo; } + } + + /// + /// Gets a System.Boolean that determines whether this math.Angle + /// is an obtuse angle (i.e. greater than 90° but less than 180°). + /// + [DataMemberIgnore] + public bool IsObtuse + { + get { return radians > MathUtil.PiOverTwo && radians < MathUtil.Pi; } + } + + /// + /// Gets a System.Boolean that determines whether this math.Angle + /// is a reflex angle (i.e. greater than 180° but less than 360°). + /// + [DataMemberIgnore] + public bool IsReflex + { + get { return radians > MathUtil.Pi && radians < MathUtil.TwoPi; } + } + + /// + /// Gets a math.AngleSingle instance that complements this angle (i.e. the two angles add to 90°). + /// + [DataMemberIgnore] + public AngleSingle Complement + { + get { return new AngleSingle( MathUtil.PiOverTwo - radians, AngleType.Radian ); } + } + + /// + /// Gets a math.AngleSingle instance that supplements this angle (i.e. the two angles add to 180°). + /// + [DataMemberIgnore] + public AngleSingle Supplement + { + get { return new AngleSingle( MathUtil.Pi - radians, AngleType.Radian ); } + } + + /// + /// Wraps the math.AngleSingle given in the value argument to be in the range [π, -π]. + /// + /// A math.AngleSingle to wrap. + /// The math.AngleSingle that is wrapped. + public static AngleSingle Wrap( AngleSingle value ) + { + value.Wrap(); + return value; + } + + /// + /// Wraps the math.AngleSingle given in the value argument to be in the range [0, 2π). + /// + /// A math.AngleSingle to wrap. + /// The math.AngleSingle that is wrapped. + public static AngleSingle WrapPositive( AngleSingle value ) + { + value.WrapPositive(); + return value; + } + + /// + /// Compares two math.AngleSingle instances and returns the smaller angle. + /// + /// The first math.AngleSingle instance to compare. + /// The second math.AngleSingle instance to compare. + /// The smaller of the two given math.AngleSingle instances. + public static AngleSingle Min( AngleSingle left, AngleSingle right ) + { + if( left.radians < right.radians ) + return left; + + return right; + } + + /// + /// Compares two math.AngleSingle instances and returns the greater angle. + /// + /// The first math.AngleSingle instance to compare. + /// The second math.AngleSingle instance to compare. + /// The greater of the two given math.AngleSingle instances. + public static AngleSingle Max( AngleSingle left, AngleSingle right ) + { + if( left.radians > right.radians ) + return left; + + return right; + } + + /// + /// Adds two math.AngleSingle objects and returns the result. + /// + /// The first object to add. + /// The second object to add. + /// The value of the two objects added together. + public static AngleSingle Add( AngleSingle left, AngleSingle right ) + { + return new AngleSingle( left.radians + right.radians, AngleType.Radian ); + } + + /// + /// Subtracts two math.AngleSingle objects and returns the result. + /// + /// The first object to subtract. + /// The second object to subtract. + /// The value of the two objects subtracted. + public static AngleSingle Subtract( AngleSingle left, AngleSingle right ) + { + return new AngleSingle( left.radians - right.radians, AngleType.Radian ); + } + + /// + /// Multiplies two math.AngleSingle objects and returns the result. + /// + /// The first object to multiply. + /// The second object to multiply. + /// The value of the two objects multiplied together. + public static AngleSingle Multiply( AngleSingle left, AngleSingle right ) + { + return new AngleSingle( left.radians * right.radians, AngleType.Radian ); + } + + /// + /// Divides two math.AngleSingle objects and returns the result. + /// + /// The numerator object. + /// The denominator object. + /// The value of the two objects divided. + public static AngleSingle Divide( AngleSingle left, AngleSingle right ) + { + return new AngleSingle( left.radians / right.radians, AngleType.Radian ); + } + + /// + /// Gets a new math.AngleSingle instance that represents the zero angle (i.e. 0°). + /// + public static AngleSingle ZeroAngle + { + get { return new AngleSingle( 0.0f, AngleType.Radian ); } + } + + /// + /// Gets a new math.AngleSingle instance that represents the right angle (i.e. 90° or π/2). + /// + public static AngleSingle RightAngle + { + get { return new AngleSingle( MathUtil.PiOverTwo, AngleType.Radian ); } + } + + /// + /// Gets a new math.AngleSingle instance that represents the straight angle (i.e. 180° or π). + /// + public static AngleSingle StraightAngle + { + get { return new AngleSingle( MathUtil.Pi, AngleType.Radian ); } + } + + /// + /// Gets a new math.AngleSingle instance that represents the full rotation angle (i.e. 360° or 2π). + /// + public static AngleSingle FullRotationAngle + { + get { return new AngleSingle( MathUtil.TwoPi, AngleType.Radian ); } + } + + /// + /// Returns a System.Boolean that indicates whether the values of two math.Angle + /// objects are equal. + /// + /// The first object to compare. + /// The second object to compare. + /// True if the left and right parameters have the same value; otherwise, false. + public static bool operator ==( AngleSingle left, AngleSingle right ) + { + return left.radians == right.radians; + } + + /// + /// Returns a System.Boolean that indicates whether the values of two math.Angle + /// objects are not equal. + /// + /// The first object to compare. + /// The second object to compare. + /// True if the left and right parameters do not have the same value; otherwise, false. + public static bool operator !=( AngleSingle left, AngleSingle right ) + { + return left.radians != right.radians; + } + + /// + /// Returns a System.Boolean that indicates whether a math.Angle + /// object is less than another math.AngleSingle object. + /// + /// The first object to compare. + /// The second object to compare. + /// True if left is less than right; otherwise, false. + public static bool operator <( AngleSingle left, AngleSingle right ) + { + return left.radians < right.radians; + } + + /// + /// Returns a System.Boolean that indicates whether a math.Angle + /// object is greater than another math.AngleSingle object. + /// + /// The first object to compare. + /// The second object to compare. + /// True if left is greater than right; otherwise, false. + public static bool operator >( AngleSingle left, AngleSingle right ) + { + return left.radians > right.radians; + } + + /// + /// Returns a System.Boolean that indicates whether a math.Angle + /// object is less than or equal to another math.AngleSingle object. + /// + /// The first object to compare. + /// The second object to compare. + /// True if left is less than or equal to right; otherwise, false. + public static bool operator <=( AngleSingle left, AngleSingle right ) + { + return left.radians <= right.radians; + } + + /// + /// Returns a System.Boolean that indicates whether a math.Angle + /// object is greater than or equal to another math.AngleSingle object. + /// + /// The first object to compare. + /// The second object to compare. + /// True if left is greater than or equal to right; otherwise, false. + public static bool operator >=( AngleSingle left, AngleSingle right ) + { + return left.radians >= right.radians; + } + + /// + /// Returns the value of the math.AngleSingle operand. (The sign of + /// the operand is unchanged.) + /// + /// A math.AngleSingle object. + /// The value of the value parameter. + public static AngleSingle operator +( AngleSingle value ) + { + return value; + } + + /// + /// Returns the the negated value of the math.AngleSingle operand. + /// + /// A math.AngleSingle object. + /// The negated value of the value parameter. + public static AngleSingle operator -( AngleSingle value ) + { + return new AngleSingle( -value.radians, AngleType.Radian ); + } + + /// + /// Adds two math.AngleSingle objects and returns the result. + /// + /// The first object to add. + /// The second object to add. + /// The value of the two objects added together. + public static AngleSingle operator +( AngleSingle left, AngleSingle right ) + { + return new AngleSingle( left.radians + right.radians, AngleType.Radian ); + } + + /// + /// Subtracts two math.AngleSingle objects and returns the result. + /// + /// The first object to subtract + /// The second object to subtract. + /// The value of the two objects subtracted. + public static AngleSingle operator -( AngleSingle left, AngleSingle right ) + { + return new AngleSingle( left.radians - right.radians, AngleType.Radian ); + } + + /// + /// Multiplies two math.AngleSingle objects and returns the result. + /// + /// The first object to multiply. + /// The second object to multiply. + /// The value of the two objects multiplied together. + public static AngleSingle operator *( AngleSingle left, AngleSingle right ) + { + return new AngleSingle( left.radians * right.radians, AngleType.Radian ); + } + + /// + /// Divides two math.AngleSingle objects and returns the result. + /// + /// The numerator object. + /// The denominator object. + /// The value of the two objects divided. + public static AngleSingle operator /( AngleSingle left, AngleSingle right ) + { + return new AngleSingle( left.radians / right.radians, AngleType.Radian ); + } + + /// + /// Compares this instance to a specified object and returns an integer that + /// indicates whether the value of this instance is less than, equal to, or greater + /// than the value of the specified object. + /// + /// The object to compare. + /// + /// A signed integer that indicates the relationship of the current instance + /// to the obj parameter. If the value is less than zero, the current instance + /// is less than the other. If the value is zero, the current instance is equal + /// to the other. If the value is greater than zero, the current instance is + /// greater than the other. + /// + public int CompareTo( object other ) + { + if( other == null ) + return 1; + + if( !( other is AngleSingle ) ) + throw new ArgumentException( "Argument must be of type Angle.", "other" ); + + float radians = ((AngleSingle)other).radians; + + if( this.radians > radians ) + return 1; + + if( this.radians < radians ) + return -1; + + return 0; + } + + /// + /// Compares this instance to a second math.AngleSingle and returns + /// an integer that indicates whether the value of this instance is less than, + /// equal to, or greater than the value of the specified object. + /// + /// The object to compare. + /// + /// A signed integer that indicates the relationship of the current instance + /// to the obj parameter. If the value is less than zero, the current instance + /// is less than the other. If the value is zero, the current instance is equal + /// to the other. If the value is greater than zero, the current instance is + /// greater than the other. + /// + public int CompareTo( AngleSingle other ) + { + if( this.radians > other.radians ) + return 1; + + if( this.radians < other.radians ) + return -1; + + return 0; + } + + /// + /// Returns a value that indicates whether the current instance and a specified + /// math.AngleSingle object have the same value. + /// + /// The object to compare. + /// + /// Returns true if this math.AngleSingle object and another have the same value; + /// otherwise, false. + /// + public bool Equals( AngleSingle other ) + { + return this == other; + } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() + { + return string.Format( CultureInfo.CurrentCulture, MathUtil.RadiansToDegrees( radians ).ToString( "0.##°" ) ); + } + + /// + /// Returns a that represents this instance. + /// + /// The format. + /// + /// A that represents this instance. + /// + public string ToString( string format ) + { + if( format == null ) + return ToString(); + + return string.Format( CultureInfo.CurrentCulture, $"{MathUtil.RadiansToDegrees( radians ).ToString( format, CultureInfo.CurrentCulture )}°" ); + } + + /// + /// Returns a that represents this instance. + /// + /// The format provider. + /// + /// A that represents this instance. + /// + public string ToString( IFormatProvider formatProvider ) + { + return string.Format( formatProvider, MathUtil.RadiansToDegrees( radians ).ToString( "0.##°" ) ); + } + + /// + /// Returns a that represents this instance. + /// + /// The format. + /// The format provider. + /// + /// A that represents this instance. + /// + public string ToString( string format, IFormatProvider formatProvider ) + { + if( format == null ) + return ToString( formatProvider ); + + return string.Format( formatProvider, "{0}°", MathUtil.RadiansToDegrees( radians ).ToString( format, CultureInfo.CurrentCulture ) ); + } + + /// + /// Returns a hash code for this math.AngleSingle instance. + /// + /// A 32-bit signed integer hash code. + public override int GetHashCode() + { + return (int)( BitConverter.DoubleToInt64Bits( radians ) % int.MaxValue ); + } + + /// + /// Returns a value that indicates whether the current instance and a specified + /// object have the same value. + /// + /// The object to compare. + /// + /// Returns true if the obj parameter is a math.AngleSingle object or a type + /// capable of implicit conversion to a math.AngleSingle value, and + /// its value is equal to the value of the current math.Angle + /// object; otherwise, false. + /// + public override bool Equals( object obj ) + { + return ( obj is AngleSingle ) && ( this == (AngleSingle)obj ); + } + } } diff --git a/mod/Modules.cs b/mod/Modules.cs index 0e82f4b..073dc2e 100644 --- a/mod/Modules.cs +++ b/mod/Modules.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; -//using System.Threading.Tasks; +using System.Text; +//using System.Threading.Tasks; using System.Diagnostics; using System.Reflection; @@ -10,7 +10,7 @@ namespace mod { [Serializable] - public class Config : lib.Config + public class Config: lib.Config { public String name = "Generic"; } @@ -33,13 +33,13 @@ namespace mod [Serializable] - public class FluidConfig : Config + public class FluidConfig: Config { public String type = "none"; } - public class FluidBase : Base + public class FluidBase: Base { public new FluidConfig Cfg { get { return (FluidConfig)base.Cfg; } } @@ -65,7 +65,7 @@ namespace mod [Serializable] - public class SystemConfig : Config + public class SystemConfig: Config { public String type = "none"; } diff --git a/net/Conn.cs b/net/Conn.cs index 22e9ed2..4c915ec 100644 --- a/net/Conn.cs +++ b/net/Conn.cs @@ -20,7 +20,7 @@ namespace lib public interface ISerDes where T : IFormatter { - + T getInstance(); @@ -28,7 +28,7 @@ namespace lib } - public class NewEveryCall : ISerDes where T : IFormatter, new() + public class NewEveryCall: ISerDes where T : IFormatter, new() { public T getInstance() { @@ -38,7 +38,7 @@ namespace lib public class Conn where T : IFormatter, new() - where TInst : ISerDes, new() + where TInst : ISerDes, new() { public Socket Sock { get { return m_socket; } } public Stream Stream { get { return m_streamNet; } } @@ -75,7 +75,7 @@ namespace lib } catch( System.Xml.XmlException ex ) { - lib.Log.error( $"Outer Exception {ex.Message}" ); + log.error( $"Outer Exception {ex.Message}" ); } return obj; @@ -92,8 +92,8 @@ namespace lib formatter.Serialize( ms, obj ); //var str = System.Text.Encoding.Default.GetString( mm_buffer, 0, (int)ms.Position ); - //lib.Log.info( $"Sent data {str} of length {ms.Position}" ); - //lib.Log.info( $"Sent {obj}" ); + //log.info( $"Sent data {str} of length {ms.Position}" ); + //log.info( $"Sent {obj}" ); byte[] byteSize = BitConverter.GetBytes( (uint)ms.Position ); m_streamNet.Write( byteSize, 0, 4 ); @@ -103,7 +103,7 @@ namespace lib } catch( Exception e ) { - lib.Log.warn( $"Exception sending obj {obj} of {e}" ); + log.warn( $"Exception sending obj {obj} of {e}" ); throw; } } diff --git a/net/NetMsg.cs b/net/NetMsg.cs index cb67582..775ffb4 100644 --- a/net/NetMsg.cs +++ b/net/NetMsg.cs @@ -1,95 +1,95 @@ -using System; - -namespace lib.Net -{ - [Serializable] - public class Msg - { - public Msg() - { - } - } - - [Serializable] - public class Login - { - public Login( String name, String pass ) - { - m_username = name; - m_password = pass; - } +using System; - public readonly String m_username; - public readonly String m_password; - } - - [Serializable] - public class LoginResp - { - public LoginResp( bool resp ) - { - m_resp = resp; +namespace lib.Net +{ + [Serializable] + public class Msg + { + public Msg() + { } - - public readonly bool m_resp; } - #region Admin Messages + [Serializable] + public class Login + { + public Login( String name, String pass ) + { + m_username = name; + m_password = pass; + } + + public readonly String m_username; + public readonly String m_password; + } + + [Serializable] + public class LoginResp + { + public LoginResp( bool resp ) + { + m_resp = resp; + } + + public readonly bool m_resp; + } + + #region Admin Messages //Subclasses of this need to be on an admin client. - [Serializable] - public class Admin + [Serializable] + public class Admin { - }; - - [Serializable] - public class CreateEntity : Admin + }; + + [Serializable] + public class CreateEntity: Admin { - } - - - [Serializable] - public class MoveEntity : Admin - { - } - #endregion - [Serializable] - public class EntityBase - { - public EntityBase( int id ) - { - m_id = id; + + [Serializable] + public class MoveEntity: Admin + { + + } + #endregion + + [Serializable] + public class EntityBase + { + public EntityBase( int id ) + { + m_id = id; } - public readonly int m_id; - }; - - - [Serializable] - public class EntityPos : EntityBase - { - public EntityPos( int id, float x, float y, float z ) : - base( id ) - { - m_x = x; - m_y = y; - m_z = z; + public readonly int m_id; + }; + + + [Serializable] + public class EntityPos: EntityBase + { + public EntityPos( int id, float x, float y, float z ) : + base( id ) + { + m_x = x; + m_y = y; + m_z = z; } - public readonly float m_x; - public readonly float m_y; - public readonly float m_z; - } - - [Serializable] - public class EntityDesc : EntityBase - { - public EntityDesc( int id ) : - base( id ) - { + public readonly float m_x; + public readonly float m_y; + public readonly float m_z; + } + + [Serializable] + public class EntityDesc: EntityBase + { + public EntityDesc( int id ) : + base( id ) + { } //Should an entity have a mesh? Be made up of multiple meshes? @@ -100,4 +100,4 @@ namespace lib.Net -} +} diff --git a/reflect/Scr.cs b/reflect/refl.cs similarity index 90% rename from reflect/Scr.cs rename to reflect/refl.cs index 3adcab3..eebb8f3 100644 --- a/reflect/Scr.cs +++ b/reflect/refl.cs @@ -14,7 +14,7 @@ using System.Threading.Tasks; -static public class scr +static public class refl { public class PredEnumerator @@ -30,7 +30,7 @@ static public class scr } } - public class PredEnumerator : PredEnumerator, IEnumerator + public class PredEnumerator: PredEnumerator, IEnumerator { public T Current => m_en.Current; @@ -100,12 +100,12 @@ static public class scr } #endregion - IEnumerator m_en; - Predicate m_pred; + IEnumerator m_en; + Predicate m_pred; } - public class PredEnumerable : IEnumerable + public class PredEnumerable: IEnumerable { public PredEnumerable( PredEnumerator en ) { @@ -132,7 +132,7 @@ static public class scr BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | - BindingFlags.Instance); + BindingFlags.Instance ); var en = PredEnumerator.Create( fieldArr.AsEnumerable(), fa => fa.GetCustomAttribute( typeof( NonSerializedAttribute ) ) == null ); @@ -167,13 +167,13 @@ static public class scr var propArr = t.GetProperties( BindingFlags.DeclaredOnly | BindingFlags.NonPublic | - BindingFlags.Public | + BindingFlags.Public | BindingFlags.Instance ); - - var en = PredEnumerator.Create( propArr.AsEnumerable(), + + var en = PredEnumerator.Create( propArr.AsEnumerable(), fa => fa.GetCustomAttribute( typeof( NonSerializedAttribute ) ) == null && !list.Exists( f => f.Name == fa.Name ) ); list.AddRange( new PredEnumerable( en ) ); diff --git a/res/Resource.cs b/res/Resource.cs index 2f8eb53..ccd7d67 100644 --- a/res/Resource.cs +++ b/res/Resource.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; -//using System.Threading.Tasks; +using System.Text; +//using System.Threading.Tasks; using System.Diagnostics; using System.Reflection; using System.Collections.Immutable; @@ -16,11 +16,11 @@ namespace res [Serializable] - public class Ref : lib.I_Serialize + public class Ref: lib.I_Serialize { - public string filename { get { return m_filename; } } - - //For construction + public string filename { get { return m_filename; } } + + //For construction public Ref() { } @@ -51,11 +51,11 @@ namespace res } [Serializable] - public class Ref : Ref where T : class + public class Ref: Ref where T : class { - public T res => m_res != null ? m_res : m_res = Mgr.load( filename ); - - //For serialization + public T res => m_res != null ? m_res : m_res = Mgr.load( filename ); + + //For serialization public Ref() { } @@ -88,9 +88,9 @@ namespace res { static public Mgr mgr; - } - - + } + + /* public class Loader { @@ -100,8 +100,8 @@ namespace res return default(T); } } - */ - + */ + public delegate T Load( string filename ); @@ -114,7 +114,7 @@ namespace res } - class LoadHolder : LoadHolder + class LoadHolder: LoadHolder { public LoadHolder( Load _dlgtLoad ) { @@ -128,9 +128,9 @@ namespace res { return load(); } - } - - //generic classes make a new static per generic type + } + + //generic classes make a new static per generic type class ResCache where T : class { public static T s_default = default; @@ -157,10 +157,10 @@ namespace res var lh = new LoadHolder( loader ); ImmutableInterlocked.TryAdd( ref Resource.mgr.m_loaders, typeof( T ), lh ); - } - - //Register all subclasses of a particular type - //???? Should we just always do this? + } + + //Register all subclasses of a particular type + //???? Should we just always do this? static public void registerSub( Type baseType ) { @@ -201,7 +201,7 @@ namespace res static public Ref lookup( string filename ) where T : class - { + { /* LoadHolder loader_gen; Resource.mgr.m_loaders.TryGetValue( typeof( T ), out loader_gen ); @@ -214,14 +214,14 @@ namespace res Ref rf = rf_raw as Ref; return rf; } - */ - + */ + return new Ref( filename ); - } - - //* + } + + //* static public Ref lookup( string filename, Type t ) - { + { /* LoadHolder loader_gen; Resource.mgr.m_loaders.TryGetValue( t, out loader_gen ); @@ -234,12 +234,12 @@ namespace res var rf_raw = loaderHolder.load( filename ); return rf_raw; } - */ - + */ + return new Ref( filename ); - } - //*/ - + } + //*/ + static public T load( string filename ) where T : class { if( ResCache.s_cache.TryGetValue( filename, out var wr ) ) @@ -247,10 +247,10 @@ namespace res if( wr.TryGetTarget( out var v ) ) return v; - lib.Log.info( $"{filename} was in cache, but its been dropped, reloading." ); + log.info( $"{filename} was in cache, but its been dropped, reloading." ); } - lib.Log.warn( $"Block Loading {filename}." ); + log.warn( $"Block Loading {filename}." ); var newV = actualLoad( filename ); @@ -268,7 +268,7 @@ namespace res if( wr.TryGetTarget( out var v ) ) return v; - lib.Log.error( $"{filename} was in cache, but its been dropped, reloading." ); + log.error( $"{filename} was in cache, but its been dropped, reloading." ); } } @@ -286,24 +286,24 @@ namespace res var alreadyAdded = !ImmutableInterlocked.TryAdd( ref ResCache.s_cache, filename, weak ); - evtNew.Set(); - - //Done loading + evtNew.Set(); + + //Done loading if( !ImmutableInterlocked.TryRemove( ref s_loading, filename, out var oldEvt ) ) { - lib.Log.error( $"Error removing loading event for {filename}" ); + log.error( $"Error removing loading event for {filename}" ); } if( alreadyAdded ) { - lib.Log.error( $"Key {filename} already existed, though it shouldnt." ); + log.error( $"Key {filename} already existed, though it shouldnt." ); } return v; } else { - lib.Log.error( $"Loader could not be found for type {typeof( T )}" ); + log.error( $"Loader could not be found for type {typeof( T )}" ); return ResCache.s_default; } diff --git a/ser/SerializableDictionary.cs b/ser/SerializableDictionary.cs index 8873863..6d5e99b 100644 --- a/ser/SerializableDictionary.cs +++ b/ser/SerializableDictionary.cs @@ -1,25 +1,25 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Xml.Serialization; -using System.Xml; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Formatters.Binary; -using System.IO; -using System.Security.Permissions; - -namespace lib +using System; +using System.Collections.Generic; +using System.Text; +using System.Xml.Serialization; +using System.Xml; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters.Binary; +using System.IO; +using System.Security.Permissions; + +namespace lib { [Serializable] - public class SerializableDictionary : Dictionary, IXmlSerializable, ISerializable + public class SerializableDictionary: Dictionary, IXmlSerializable, ISerializable { - #region Constants + #region Constants private const string DictionaryNodeName = "Dictionary"; private const string ItemNodeName = "Item"; private const string KeyNodeName = "Key"; private const string ValueNodeName = "Value"; - #endregion - #region Constructors + #endregion + #region Constructors public SerializableDictionary() { } @@ -49,8 +49,8 @@ namespace lib { } - #endregion - #region ISerializable Members + #endregion + #region ISerializable Members protected SerializableDictionary( SerializationInfo info, StreamingContext context ) { @@ -74,8 +74,8 @@ namespace lib } } - #endregion - #region IXmlSerializable Members + #endregion + #region IXmlSerializable Members void IXmlSerializable.WriteXml( System.Xml.XmlWriter writer ) { @@ -131,8 +131,8 @@ namespace lib return null; } - #endregion - #region Private Properties + #endregion + #region Private Properties protected XmlSerializer ValueSerializer { get @@ -156,10 +156,10 @@ namespace lib return keySerializer; } } - #endregion - #region Private Members + #endregion + #region Private Members private XmlSerializer keySerializer = null; private XmlSerializer valueSerializer = null; - #endregion - } -} + #endregion + } +} diff --git a/ser/VersionFormatter.cs b/ser/VersionFormatter.cs index bde4613..c61cb44 100644 --- a/ser/VersionFormatter.cs +++ b/ser/VersionFormatter.cs @@ -12,7 +12,7 @@ namespace lib /// /// /// - public class VersionFormatter : IFormatter + public class VersionFormatter: IFormatter { public enum ETypes { @@ -160,44 +160,44 @@ namespace lib switch( typeName ) { case "Int32": - writer.Write( (char)ETypes.Int32 ); - writer.Write( name.GetHashCode() ); + writer.Write( (char)ETypes.Int32 ); + writer.Write( name.GetHashCode() ); - write( writer, Convert.ToInt32( fi.GetValue( parentObj ) ) ); - break; + write( writer, Convert.ToInt32( fi.GetValue( parentObj ) ) ); + break; case "Single": - writer.Write( (char)ETypes.Single ); - writer.Write( name.GetHashCode() ); + writer.Write( (char)ETypes.Single ); + writer.Write( name.GetHashCode() ); - write( writer, Convert.ToSingle( fi.GetValue( parentObj ) ) ); - break; + write( writer, Convert.ToSingle( fi.GetValue( parentObj ) ) ); + break; case "Double": - writer.Write( (char)ETypes.Double ); - writer.Write( name.GetHashCode() ); + writer.Write( (char)ETypes.Double ); + writer.Write( name.GetHashCode() ); - write( writer, Convert.ToDouble( fi.GetValue( parentObj ) ) ); - break; + write( writer, Convert.ToDouble( fi.GetValue( parentObj ) ) ); + break; case "Char": - writer.Write( (char)ETypes.Char ); - writer.Write( name.GetHashCode() ); + writer.Write( (char)ETypes.Char ); + writer.Write( name.GetHashCode() ); - write( writer, Convert.ToChar( fi.GetValue( parentObj ) ) ); - break; + write( writer, Convert.ToChar( fi.GetValue( parentObj ) ) ); + break; case "String": - writer.Write( (char)ETypes.String ); - writer.Write( name.GetHashCode() ); + writer.Write( (char)ETypes.String ); + writer.Write( name.GetHashCode() ); - write( writer, Convert.ToString( fi.GetValue( parentObj ) ) ); - break; + write( writer, Convert.ToString( fi.GetValue( parentObj ) ) ); + break; case "Boolean": - writer.Write( (char)ETypes.Boolean ); - writer.Write( name.GetHashCode() ); + writer.Write( (char)ETypes.Boolean ); + writer.Write( name.GetHashCode() ); - writer.Write( Convert.ToBoolean( fi.GetValue( parentObj ) ) ); - break; + writer.Write( Convert.ToBoolean( fi.GetValue( parentObj ) ) ); + break; default: - Console.WriteLine( "VersionFormatter does not understand type " + typeName ); - break; + Console.WriteLine( "VersionFormatter does not understand type " + typeName ); + break; } } } @@ -433,35 +433,35 @@ namespace lib switch( type ) { case ETypes.Array: - readArray( reader, obj, fi ); - break; + readArray( reader, obj, fi ); + break; case ETypes.Int32: - readInt( reader, obj, fi ); - break; + readInt( reader, obj, fi ); + break; case ETypes.Single: - readSingle( reader, obj, fi ); - break; + readSingle( reader, obj, fi ); + break; case ETypes.Double: - readDouble( reader, obj, fi ); - break; + readDouble( reader, obj, fi ); + break; case ETypes.Char: - readChar( reader, obj, fi ); - break; + readChar( reader, obj, fi ); + break; case ETypes.Boolean: - readBool( reader, obj, fi ); - break; + readBool( reader, obj, fi ); + break; case ETypes.String: - readString( reader, obj, fi ); - break; + readString( reader, obj, fi ); + break; case ETypes.Ref: - readRef( reader, obj, fi ); - break; + readRef( reader, obj, fi ); + break; case ETypes.Object: - readObject( reader ); - break; + readObject( reader ); + break; default: - Debug.Fail( "Unknown type on read." ); - break; + Debug.Fail( "Unknown type on read." ); + break; } } catch( Exception ex ) diff --git a/ser/XmlFormatter.cs b/ser/XmlFormatter.cs index 310b083..e1df418 100644 --- a/ser/XmlFormatter.cs +++ b/ser/XmlFormatter.cs @@ -1,12 +1,12 @@ -using System; -using System.IO; -using System.Xml; -using System.Runtime.Serialization; -//using System.Web.Configuration; -using System.Collections; -using System.Collections.Generic; - - +using System; +using System.IO; +using System.Xml; +using System.Runtime.Serialization; +//using System.Web.Configuration; +using System.Collections; +using System.Collections.Generic; + + using System.Reflection; //using System.Collections; //using System.Diagnostics; @@ -14,37 +14,37 @@ using System.Reflection; //using System.ComponentModel; -namespace lib +namespace lib { //Old, use 2 now. - class XmlFormatter : IFormatter - { - StreamingContext m_context; + class XmlFormatter: IFormatter + { + StreamingContext m_context; //SerializationMode m_mode; //KnownTypeCollection known_types; //IDataContractSurrogate m_surrogate; //int m_maxItems; - public XmlFormatter() - { - } + public XmlFormatter() + { + } - /* - public XmlFormatter( SerializationMode mode ) - { - m_mode = mode; - } - - public XmlFormatter( StreamingContext context ) - { - m_context = context; - } - - public XmlFormatter( SerializationMode mode, - StreamingContext context ) - { - m_mode = mode; - m_context = context; + /* + public XmlFormatter( SerializationMode mode ) + { + m_mode = mode; + } + + public XmlFormatter( StreamingContext context ) + { + m_context = context; + } + + public XmlFormatter( SerializationMode mode, + StreamingContext context ) + { + m_mode = mode; + m_context = context; } */ @@ -54,185 +54,185 @@ namespace lib //} SerializationBinder IFormatter.Binder - { - get { throw new NotImplementedException(); } - set { throw new NotImplementedException(); } - } - - ISurrogateSelector IFormatter.SurrogateSelector - { - get { throw new NotImplementedException(); } - set { throw new NotImplementedException(); } - } - - public StreamingContext Context - { - get { return m_context; } - set { m_context = value; } - } - + { + get { throw new NotImplementedException(); } + set { throw new NotImplementedException(); } + } - /* - public KnownTypeCollection KnownTypes { - get { return known_types; } - } - - public int MaxItemsInObjectGraph { - get { return m_maxItems; } - set { m_maxItems= value; } - } + ISurrogateSelector IFormatter.SurrogateSelector + { + get { throw new NotImplementedException(); } + set { throw new NotImplementedException(); } + } + + public StreamingContext Context + { + get { return m_context; } + set { m_context = value; } + } + + + /* + public KnownTypeCollection KnownTypes { + get { return known_types; } + } + + public int MaxItemsInObjectGraph { + get { return m_maxItems; } + set { m_maxItems= value; } + } */ - - object IFormatter.Deserialize( Stream stream ) - { - return Deserialize( stream, null ); - } - - public object Deserialize( Stream stream, Type type ) - { - XmlTextReader reader = new XmlTextReader( stream ); - - return Deserialize( reader, type ); - } - - public object Deserialize( XmlReader reader, Type type ) - { - return Deserialize( reader, type, false ); - } - - public object Deserialize( XmlReader reader, Type type, bool readContentOnly ) - { - reader.Read(); - - XmlDocument doc = new XmlDocument(); - - doc.Load( reader ); - - return Deserialize( doc.DocumentElement ); - } - - ConstructorInfo getNoParamCons( ConstructorInfo[] ciArr ) - { - foreach( ConstructorInfo ci in ciArr ) - { - if( ci.GetParameters().Length == 0 ) - { - return ci; - } - } - - return null; - } - - private static FormatterConverter s_conv = new FormatterConverter(); - - private Dictionary m_alreadySerialized = new Dictionary(); - - public object Deserialize( XmlElement elem ) - { - string strType = elem.GetAttribute( "t" ); - - return Deserialize( elem, strType ); - } - - public object Deserialize( XmlElement elem, string strType ) - { - Type type = Type.GetType( strType ); - - MemberInfo[] miArr = FormatterServices.GetSerializableMembers( type ); - + + object IFormatter.Deserialize( Stream stream ) + { + return Deserialize( stream, null ); + } + + public object Deserialize( Stream stream, Type type ) + { + XmlTextReader reader = new XmlTextReader( stream ); + + return Deserialize( reader, type ); + } + + public object Deserialize( XmlReader reader, Type type ) + { + return Deserialize( reader, type, false ); + } + + public object Deserialize( XmlReader reader, Type type, bool readContentOnly ) + { + reader.Read(); + + XmlDocument doc = new XmlDocument(); + + doc.Load( reader ); + + return Deserialize( doc.DocumentElement ); + } + + ConstructorInfo getNoParamCons( ConstructorInfo[] ciArr ) + { + foreach( ConstructorInfo ci in ciArr ) + { + if( ci.GetParameters().Length == 0 ) + { + return ci; + } + } + + return null; + } + + private static FormatterConverter s_conv = new FormatterConverter(); + + private Dictionary m_alreadySerialized = new Dictionary(); + + public object Deserialize( XmlElement elem ) + { + string strType = elem.GetAttribute( "t" ); + + return Deserialize( elem, strType ); + } + + public object Deserialize( XmlElement elem, string strType ) + { + Type type = Type.GetType( strType ); + + MemberInfo[] miArr = FormatterServices.GetSerializableMembers( type ); + object obj = Activator.CreateInstance( type ); - /* - object obj = FormatterServices.GetUninitializedObject( type ); - - - ConstructorInfo[] ciArr = obj.GetType().GetConstructors(); - - ConstructorInfo ci = getNoParamCons( ciArr ); - - if( ci == null ) - return null; - - obj = ci.Invoke( null ); + /* + object obj = FormatterServices.GetUninitializedObject( type ); + + + ConstructorInfo[] ciArr = obj.GetType().GetConstructors(); + + ConstructorInfo ci = getNoParamCons( ciArr ); + + if( ci == null ) + return null; + + obj = ci.Invoke( null ); */ - for( int i = 0; i < miArr.Length; ++i ) - { - FieldInfo fi = (FieldInfo)miArr[ i ]; - - XmlNodeList nodeList = elem.GetElementsByTagName( fi.Name ); - - if( nodeList.Count == 1 ) - { - Type t = fi.FieldType; - - TypeCode tc = Type.GetTypeCode( t ); - - XmlElement child = (XmlElement)nodeList[ 0 ]; - - object childObj = null; - - if( tc != TypeCode.Object || fi.FieldType.FullName == "System.String" ) - { - childObj = s_conv.Convert( child.GetAttribute( "v" ), fi.FieldType ); - } - else - { - if( !t.IsArray ) - { - string refStr = child.GetAttribute( "ref" ); - int refInt = Convert.ToInt32( refStr ); - - if( child.HasAttribute( "t" ) ) - { - childObj = Deserialize( child ); - - m_alreadySerialized[refInt] = childObj; - } - else - { - childObj = m_alreadySerialized[refInt]; - } - } - else + for( int i = 0; i < miArr.Length; ++i ) + { + FieldInfo fi = (FieldInfo)miArr[ i ]; + + XmlNodeList nodeList = elem.GetElementsByTagName( fi.Name ); + + if( nodeList.Count == 1 ) + { + Type t = fi.FieldType; + + TypeCode tc = Type.GetTypeCode( t ); + + XmlElement child = (XmlElement)nodeList[ 0 ]; + + object childObj = null; + + if( tc != TypeCode.Object || fi.FieldType.FullName == "System.String" ) + { + childObj = s_conv.Convert( child.GetAttribute( "v" ), fi.FieldType ); + } + else + { + if( !t.IsArray ) + { + string refStr = child.GetAttribute( "ref" ); + int refInt = Convert.ToInt32( refStr ); + + if( child.HasAttribute( "t" ) ) + { + childObj = Deserialize( child ); + + m_alreadySerialized[refInt] = childObj; + } + else + { + childObj = m_alreadySerialized[refInt]; + } + } + else { //FormatterServices.GetUninitializedObject() - int length = s_conv.ToInt32( child.GetAttribute( "c" ) ); - - string elemType = child.GetAttribute( "t" ); - - Array arr = Array.CreateInstance( t.GetElementType(), length ); - - XmlNodeList arrNodeList = child.ChildNodes; - - for( int iElems = 0; iElems < arr.Length; ++iElems ) - { - XmlElement arrElem = (XmlElement)arrNodeList.Item( iElems ); - - arr.SetValue( Deserialize( arrElem, elemType ), iElems ); - } - } - } - - fi.SetValue( obj, childObj ); - } - else - { - if( nodeList.Count == 0 ) + int length = s_conv.ToInt32( child.GetAttribute( "c" ) ); + + string elemType = child.GetAttribute( "t" ); + + Array arr = Array.CreateInstance( t.GetElementType(), length ); + + XmlNodeList arrNodeList = child.ChildNodes; + + for( int iElems = 0; iElems < arr.Length; ++iElems ) + { + XmlElement arrElem = (XmlElement)arrNodeList.Item( iElems ); + + arr.SetValue( Deserialize( arrElem, elemType ), iElems ); + } + } + } + + fi.SetValue( obj, childObj ); + } + else + { + if( nodeList.Count == 0 ) { // Should be //object obj2 = fi.GetRawConstantValue(); - } + } else //More than 1. { - //Log.error( "Too many fields named the same thing" ); - } - } + //log.error( "Too many fields named the same thing" ); + } + } } //FieldInfo fi = (FieldInfo)miArr[0]; @@ -241,144 +241,144 @@ namespace lib //ci.Invoke( null ); - return obj; + return obj; } - /* - public T Deserialize (Stream stream) - { - return (T) Deserialize (XmlReader.Create (stream), typeof (T)); - } - - public T Deserialize (XmlReader reader) - { - return (T) Deserialize (reader, typeof (T), false); - } - - public T Deserialize (XmlReader reader, bool readContentOnly) - { - return (T) Deserialize (reader, typeof (T), readContentOnly); - } + /* + public T Deserialize (Stream stream) + { + return (T) Deserialize (XmlReader.Create (stream), typeof (T)); + } + + public T Deserialize (XmlReader reader) + { + return (T) Deserialize (reader, typeof (T), false); + } + + public T Deserialize (XmlReader reader, bool readContentOnly) + { + return (T) Deserialize (reader, typeof (T), readContentOnly); + } */ - public void Serialize( Stream stream, object graph ) + public void Serialize( Stream stream, object graph ) { - /* - XmlWriterSettings settings = new XmlWriterSettings(); - - settings.Indent = true; - - Serialize( XmlWriter.Create( stream, settings ), graph ); + /* + XmlWriterSettings settings = new XmlWriterSettings(); + + settings.Indent = true; + + Serialize( XmlWriter.Create( stream, settings ), graph ); */ - XmlTextWriter writer = new XmlTextWriter( stream, null ); - - writer.Formatting = Formatting.Indented; - - Serialize( writer, graph ); - - writer.Close(); - } - - public void Serialize( XmlWriter writer, object graph ) - { - Serialize( writer, graph, null, true, false, true ); - } - - public void Serialize( XmlWriter writer, object graph, - Type rootType, bool preserveObjectReferences, - bool writeContentOnly, - bool ignoreUnknownSerializationData ) - { + XmlTextWriter writer = new XmlTextWriter( stream, null ); + + writer.Formatting = Formatting.Indented; + + Serialize( writer, graph ); + + writer.Close(); + } + + public void Serialize( XmlWriter writer, object graph ) + { + Serialize( writer, graph, null, true, false, true ); + } + + public void Serialize( XmlWriter writer, object graph, + Type rootType, bool preserveObjectReferences, + bool writeContentOnly, + bool ignoreUnknownSerializationData ) + { Type t = graph.GetType(); //writer.WriteStartDocument(); - if( Type.GetTypeCode( t ) == TypeCode.Object ) - { - writer.WriteStartElement( "root" ); - - Assembly assem = t.Assembly; - - string assemName = assem.GetName().Name; - - writer.WriteAttributeString( "t", graph.GetType().FullName + ", " + assemName ); - - FieldInfo[] fiArr = t.GetFields( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly ); - - foreach( FieldInfo fi in fiArr ) - { + if( Type.GetTypeCode( t ) == TypeCode.Object ) + { + writer.WriteStartElement( "root" ); + + Assembly assem = t.Assembly; + + string assemName = assem.GetName().Name; + + writer.WriteAttributeString( "t", graph.GetType().FullName + ", " + assemName ); + + FieldInfo[] fiArr = t.GetFields( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly ); + + foreach( FieldInfo fi in fiArr ) + { Serialize( writer, fi.Name, fi.GetValue( graph ) ); - /* - if( fi.FieldType.IsClass ) - { - Serialize( writer, fi.GetValue( graph ), rootType, preserveObjectReferences, writeContentOnly, ignoreUnknownSerializationData ); - } - else - { - SerializePod( writer, fi.GetValue( graph ) ); - } + /* + if( fi.FieldType.IsClass ) + { + Serialize( writer, fi.GetValue( graph ), rootType, preserveObjectReferences, writeContentOnly, ignoreUnknownSerializationData ); + } + else + { + SerializePod( writer, fi.GetValue( graph ) ); + } */ - } - - writer.WriteEndElement(); + } + + writer.WriteEndElement(); } //writer.WriteEndDocument(); - } - - private ObjectIDGenerator m_idGenerator = new ObjectIDGenerator(); - private Dictionary m_alreadyDeserialzied = new Dictionary(); - - public void Serialize( XmlWriter writer, string name, object obj ) - { - writer.WriteStartElement( name ); - - if( obj != null ) - { - Type t = obj.GetType(); - - if( Type.GetTypeCode( t ) == TypeCode.Object ) - { - bool first = false; - if( !m_alreadyDeserialzied.ContainsKey( m_idGenerator.GetId( obj, out first ) ) ) - { - m_alreadyDeserialzied[m_idGenerator.GetId( obj, out first )] = obj; - - Assembly assem = t.Assembly; - - string assemName = assem.GetName().Name; - - if( !t.IsArray ) - { - writer.WriteAttributeString( "t", t.FullName + ", " + assemName ); - - writer.WriteAttributeString( "ref", m_idGenerator.GetId( obj, out first ).ToString() ); - - FieldInfo[] fiArr = t.GetFields( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public ); - - foreach( FieldInfo fi in fiArr ) - { - Serialize( writer, fi.Name, fi.GetValue( obj ) ); - } - } - else - { - Array arr = (Array)obj; - - Type aType = t.GetElementType(); - - string aTypeString = aType.FullName; - - writer.WriteAttributeString( "t", aTypeString + ", " + assemName ); - - writer.WriteAttributeString( "c", arr.Length.ToString() ); - - for( int i = 0; i < arr.Length; ++i ) - { - Serialize( writer, "val", arr.GetValue( i ) ); + } + + private ObjectIDGenerator m_idGenerator = new ObjectIDGenerator(); + private Dictionary m_alreadyDeserialzied = new Dictionary(); + + public void Serialize( XmlWriter writer, string name, object obj ) + { + writer.WriteStartElement( name ); + + if( obj != null ) + { + Type t = obj.GetType(); + + if( Type.GetTypeCode( t ) == TypeCode.Object ) + { + bool first = false; + if( !m_alreadyDeserialzied.ContainsKey( m_idGenerator.GetId( obj, out first ) ) ) + { + m_alreadyDeserialzied[m_idGenerator.GetId( obj, out first )] = obj; + + Assembly assem = t.Assembly; + + string assemName = assem.GetName().Name; + + if( !t.IsArray ) + { + writer.WriteAttributeString( "t", t.FullName + ", " + assemName ); + + writer.WriteAttributeString( "ref", m_idGenerator.GetId( obj, out first ).ToString() ); + + FieldInfo[] fiArr = t.GetFields( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public ); + + foreach( FieldInfo fi in fiArr ) + { + Serialize( writer, fi.Name, fi.GetValue( obj ) ); + } + } + else + { + Array arr = (Array)obj; + + Type aType = t.GetElementType(); + + string aTypeString = aType.FullName; + + writer.WriteAttributeString( "t", aTypeString + ", " + assemName ); + + writer.WriteAttributeString( "c", arr.Length.ToString() ); + + for( int i = 0; i < arr.Length; ++i ) + { + Serialize( writer, "val", arr.GetValue( i ) ); } //writer.WriteStartElement( "values" ); @@ -387,29 +387,29 @@ namespace lib //writer.WriteEndElement(); - } - } - else - { - writer.WriteAttributeString( "ref", m_idGenerator.GetId( obj, out first ).ToString() ); - } - } - else - { - writer.WriteAttributeString( "t", t.FullName ); - - writer.WriteAttributeString( "v", obj.ToString() ); - } - } - else - { - writer.WriteAttributeString( "null", "" ); - } - - writer.WriteEndElement(); - } - - } + } + } + else + { + writer.WriteAttributeString( "ref", m_idGenerator.GetId( obj, out first ).ToString() ); + } + } + else + { + writer.WriteAttributeString( "t", t.FullName ); + + writer.WriteAttributeString( "v", obj.ToString() ); + } + } + else + { + writer.WriteAttributeString( "null", "" ); + } + + writer.WriteEndElement(); + } + + } } diff --git a/ser/XmlFormatter2.cs b/ser/XmlFormatter2.cs index 3fa8693..3e4774d 100644 --- a/ser/XmlFormatter2.cs +++ b/ser/XmlFormatter2.cs @@ -29,12 +29,12 @@ namespace lib } - public class XmlFormatter2Cfg : Config + public class XmlFormatter2Cfg: Config { public readonly Datastructure datastructure = Datastructure.Full; } - public class XmlFormatter2 : IFormatter + public class XmlFormatter2: IFormatter { public StreamingContext Context { get; set; } @@ -95,10 +95,10 @@ namespace lib { //lib.log.info( "DeserializeKnownType( Stream stream, Type t ) {0} {1}", m_rndVal, m_alreadySerialized.Count ); - XmlTextReader reader = new XmlTextReader( stream ); + XmlTextReader reader = new XmlTextReader(stream); //reader.Settings = System.Text.Encoding.ASCII; - object obj = Deserialize( reader, t ); + object obj = Deserialize(reader, t); //lib.log.info( "DeserializeKnownType END( Stream stream, Type t ) {0} {1}", m_rndVal, m_alreadySerialized.Count ); return obj; } @@ -128,7 +128,7 @@ namespace lib { //lib.log.info( "object Deserialize( XmlElement elem ) {0} {1}", m_rndVal, m_alreadySerialized.Count ); - string typename = elem.HasAttribute( "t" ) ? elem.GetAttribute( "t" ) : elem.Name; + string typename = elem.HasAttribute("t") ? elem.GetAttribute("t") : elem.Name; return Deserialize( elem, typename ); } @@ -160,7 +160,7 @@ namespace lib private object Deserialize( XmlElement elem, Type type, object enclosing = null ) { - TypeCode typeCode = Type.GetTypeCode( type ); + TypeCode typeCode = Type.GetTypeCode(type); if( typeCode != TypeCode.Object ) { @@ -170,7 +170,7 @@ namespace lib { if( !type.IsArray ) { - object obj = DeserializeObject( elem, type ); + object obj = DeserializeObject(elem, type); if( obj is I_Serialize ) { @@ -193,7 +193,7 @@ namespace lib { mm_types[0] = t; - var fn = GetType().GetMethod( "GetDefaultGeneric" ).MakeGenericMethod( mm_types ); + var fn = GetType().GetMethod("GetDefaultGeneric").MakeGenericMethod(mm_types); return fn.Invoke( this, null ); } @@ -205,7 +205,7 @@ namespace lib private object DeserializeConcrete( XmlElement elem, Type type ) { - string val = elem.GetAttribute( "v" ); + string val = elem.GetAttribute("v"); if( !type.IsEnum ) { @@ -244,7 +244,7 @@ namespace lib foreach( Assembly a in ass ) { - Type t = a.GetType( shortname ); + Type t = a.GetType(shortname); if( t != null ) { @@ -255,25 +255,25 @@ namespace lib return null; } - private Type[] mm_consType = new Type[ 2 ]; - private object[] mm_args = new object[ 2 ]; + private Type[] mm_consType = new Type[2]; + private object[] mm_args = new object[2]; private object DeserializeObject( XmlElement elem, Type type ) { - string refString = elem.GetAttribute( "ref" ); + string refString = elem.GetAttribute("ref"); - int refInt = refString.Length > 0 ? Convert.ToInt32( refString ) : -1; + int refInt = refString.Length > 0 ? Convert.ToInt32(refString) : -1; var finalType = type; if( elem.HasAttribute( "t" ) ) { - var typename = elem.GetAttribute( "t" ); + var typename = elem.GetAttribute("t"); finalType = FindType( typename ); if( finalType == null ) finalType = type; } - object obj = createObject( finalType, refInt ); + object obj = createObject(finalType, refInt); if( obj is IList ) { @@ -282,7 +282,7 @@ namespace lib return DeserializeList( elem, type, list ); } - Type typeISerializable = typeof( ISerializable ); + Type typeISerializable = typeof(ISerializable); if( obj is ISerializable ) // type.IsSubclassOf( typeISerializable ) ) { @@ -290,7 +290,7 @@ namespace lib //ISerializable ser = obj as ISerializable; - var serInfo = new SerializationInfo( finalType, new FormatterConverter() ); + var serInfo = new SerializationInfo(finalType, new FormatterConverter()); //var serInfoForTypes = new SerializationInfo( type, new FormatterConverter() ); @@ -302,13 +302,13 @@ namespace lib String name = node.Name; - String childType = node.GetAttribute( "t" ); + String childType = node.GetAttribute("t"); - name = scr.TypeToIdentifier( name ); + name = refl.TypeToIdentifier( name ); - XmlElement childElem = getNamedChild( allChildren, name ); + XmlElement childElem = getNamedChild(allChildren, name); - var des = Deserialize( childElem, childType ); + var des = Deserialize(childElem, childType); serInfo.AddValue( name, des, des.GetType() ); } @@ -323,7 +323,7 @@ namespace lib mm_consType[0] = typeof( SerializationInfo ); 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[1] = Context; @@ -343,7 +343,7 @@ namespace lib { String name = serMember.Name; - name = scr.TypeToIdentifier( name ); + name = refl.TypeToIdentifier( name ); XmlElement childElem = getNamedChild( allChildren, name ); @@ -355,7 +355,7 @@ namespace lib { XmlNodeList allChildren = elem.ChildNodes; - var fields = scr.GetAllFields( type ); + var fields = refl.GetAllFields(type); //MemberInfo[] miArr = FormatterServices.GetSerializableMembers( type, Context ); @@ -364,20 +364,20 @@ namespace lib String name = childFi.Name; - name = scr.TypeToIdentifier( name ); + name = refl.TypeToIdentifier( name ); - XmlElement childElem = getNamedChild( allChildren, name ); + XmlElement childElem = getNamedChild(allChildren, name); if( childElem != null ) { - object childObj = Deserialize( childElem, childFi.FieldType, obj ); + object childObj = Deserialize(childElem, childFi.FieldType, obj); childFi.SetValue( obj, childObj ); } else if( fields.Count == 1 ) { - object childObj = Deserialize( elem, childFi.FieldType, obj ); + object childObj = Deserialize(elem, childFi.FieldType, obj); childFi.SetValue( obj, childObj ); } @@ -403,7 +403,7 @@ namespace lib { if( arrNodeList.Item( i ) is XmlElement ) { - XmlElement arrElem = (XmlElement)arrNodeList.Item( i ); + XmlElement arrElem = (XmlElement)arrNodeList.Item(i); list.Add( Deserialize( arrElem, genT[0] ) ); } @@ -416,20 +416,20 @@ namespace lib { Type typeElem = type.GetElementType(); - string refString = elem.GetAttribute( "ref" ); - int refInt = refString.Length > 0 ? Convert.ToInt32( refString ) : -1; + string refString = elem.GetAttribute("ref"); + int refInt = refString.Length > 0 ? Convert.ToInt32(refString) : -1; XmlNodeList arrNodeList = elem.ChildNodes; int length = arrNodeList.Count; - Array arr = createArray( typeElem, refInt, length ); + Array arr = createArray(typeElem, refInt, length); for( int i = 0; i < arr.Length; ++i ) { if( arrNodeList.Item( i ) is XmlElement ) { - XmlElement arrElem = (XmlElement)arrNodeList.Item( i ); + XmlElement arrElem = (XmlElement)arrNodeList.Item(i); arr.SetValue( Deserialize( arrElem, typeElem ), i ); } @@ -440,14 +440,14 @@ namespace lib private object createObject( string typename, int refInt ) { - Type type = Type.GetType( typename ); + Type type = Type.GetType(typename); return createObject( type, refInt ); } private object createObject( Type type, int refInt ) { - TypeCode tc = Type.GetTypeCode( type ); + TypeCode tc = Type.GetTypeCode(type); if( m_cfg.datastructure == Datastructure.Full && refInt > 0 && m_alreadySerialized.ContainsKey( refInt ) ) { @@ -472,14 +472,14 @@ namespace lib } catch( Exception exInner ) { - lib.Log.error( $"Got exception {exInner.Message} trying to make an uninitialized object" ); + log.error( $"Got exception {exInner.Message} trying to make an uninitialized object" ); } } if( obj == null ) { - lib.Log.warn( $"Could not create object of type {type.Name}" ); + log.warn( $"Could not create object of type {type.Name}" ); return obj; } @@ -495,14 +495,14 @@ namespace lib private Array createArray( string elemTypename, int refInt, int length ) { - Type elemType = Type.GetType( elemTypename ); + Type elemType = Type.GetType(elemTypename); return createArray( elemType, refInt, length ); } private Array createArray( Type elemType, int refInt, int length ) { - TypeCode elemTC = Type.GetTypeCode( elemType ); + TypeCode elemTC = Type.GetTypeCode(elemType); if( m_cfg.datastructure == Datastructure.Full && refInt > 0 && m_alreadySerialized.ContainsKey( refInt ) ) { @@ -510,7 +510,7 @@ namespace lib } else { - Array arr = Array.CreateInstance( elemType, length ) ; + Array arr = Array.CreateInstance(elemType, length); if( m_cfg.datastructure == Datastructure.Full ) { @@ -545,7 +545,7 @@ namespace lib m_alreadySerialized.Clear(); m_objectID = new ObjectIDGenerator(); - XmlTextWriter writer = new XmlTextWriter( stream, System.Text.Encoding.ASCII ); + XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.ASCII); writer.Formatting = Formatting.Indented; @@ -573,7 +573,7 @@ namespace lib { Type type = root.GetType(); - TypeCode typeCode = Type.GetTypeCode( type ); + TypeCode typeCode = Type.GetTypeCode(type); if( typeCode != TypeCode.Object ) { @@ -626,7 +626,7 @@ namespace lib bool first; - long refInt = m_objectID.GetId( root, out first ); + long refInt = m_objectID.GetId(root, out first); if( m_cfg.datastructure == Datastructure.Full ) { @@ -644,13 +644,13 @@ namespace lib Type type = root.GetType(); //* - Type typeISerializable = typeof( ISerializable ); + Type typeISerializable = typeof(ISerializable); if( root is ISerializable ) // type.IsSubclassOf( typeISerializable ) ) { ISerializable ser = root as ISerializable; - var serInfo = new SerializationInfo( type, new FormatterConverter() ); + var serInfo = new SerializationInfo(type, new FormatterConverter()); ser.GetObjectData( serInfo, Context ); @@ -660,7 +660,7 @@ namespace lib { String name = serMember.Name; - name = scr.TypeToIdentifier( name ); + name = refl.TypeToIdentifier( name ); Serialize( writer, serMember.Value, name, true ); } @@ -672,14 +672,14 @@ namespace lib else //*/ { - var fields = scr.GetAllFields( type ); + var fields = refl.GetAllFields(type); //MemberInfo[] miArr = FormatterServices.GetSerializableMembers( type, Context ); foreach( var childFi in fields ) { - object[] objs = childFi.GetCustomAttributes( typeof( NonSerializedAttribute ), true ); + object[] objs = childFi.GetCustomAttributes(typeof(NonSerializedAttribute), true); if( objs.Length > 0 ) { @@ -688,7 +688,7 @@ namespace lib String name = childFi.Name; - name = scr.TypeToIdentifier( name ); + name = refl.TypeToIdentifier( name ); Serialize( writer, childFi.GetValue( root ), name, false ); } @@ -708,7 +708,7 @@ namespace lib bool first; - long refInt = m_objectID.GetId( root, out first ); + long refInt = m_objectID.GetId(root, out first); if( m_cfg.datastructure == Datastructure.Full ) { diff --git a/time/Timer.cs b/time/Timer.cs index 4f4cf73..76b4c22 100644 --- a/time/Timer.cs +++ b/time/Timer.cs @@ -6,7 +6,7 @@ using System.Threading; namespace lib { - public class MicroStopwatch : System.Diagnostics.Stopwatch + public class MicroStopwatch: System.Diagnostics.Stopwatch { readonly double _microSecPerTick = 1000000D / System.Diagnostics.Stopwatch.Frequency; @@ -189,7 +189,7 @@ namespace lib /// /// MicroTimer Event Argument class /// - public class MicroTimerEventArgs : EventArgs + public class MicroTimerEventArgs: EventArgs { // Simple counter, number times timed event (callback function) executed public int TimerCount { get; private set; }