Files
2025-03-13 12:04:22 -07:00

358 lines
13 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace Raytheon.Units
{
/// <summary>
/// This class represents precision time spans where the .NET TimeSpan class just does
/// not cut the mustard
///
/// It has no constructors. Instead, it provides multiple methods for creating objects of this
/// type. Those methods are of the form FromXXX, where XXX is a unit (e.g. FromSeconds).
///
/// Properties (e.g. Seconds) are provided to convert the value to other units and return
/// as type double.
///
/// Methods (operator overloads) are provided to perform calculations with related types
/// </summary>
[Serializable]
[DataContract]
public class PrecisionTimeSpan
{
public enum Unit
{
Seconds,
Milliseconds,
Microseconds,
Nanoseconds
}
public static IDictionary<Unit, List<string>> UnitAbbreviations = new Dictionary<Unit, List<string>>()
{
{Unit.Seconds, new List<string>(){ "sec" } },
{Unit.Milliseconds, new List<string>(){ "msec" } },
{Unit.Microseconds, new List<string>(){ "usec" } },
{Unit.Nanoseconds, new List<string>(){ "nsec" } },
};
private const Unit DefaultUnits = Unit.Seconds;
[DataMember(Name = "BaseTimeSpan", IsRequired = true)]
private Decimal _totalns; //base will be nano seconds... max will be double.MaxValue
//min will be 0
// map: unit => abbreviation, conversion method and property
private static IDictionary<Unit, UnitInfo<PrecisionTimeSpan>> _unitInfo = new Dictionary<Unit, UnitInfo<PrecisionTimeSpan>>()
{
{ Unit.Seconds, new UnitInfo<PrecisionTimeSpan>(UnitAbbreviations[Unit.Seconds], FromSeconds, typeof(PrecisionTimeSpan).GetProperty("Seconds").GetGetMethod()) },
{ Unit.Milliseconds, new UnitInfo<PrecisionTimeSpan>(UnitAbbreviations[Unit.Milliseconds], FromMilliseconds, typeof(PrecisionTimeSpan).GetProperty("Milliseconds").GetGetMethod()) },
{ Unit.Microseconds, new UnitInfo<PrecisionTimeSpan>(UnitAbbreviations[Unit.Microseconds], FromMicroseconds, typeof(PrecisionTimeSpan).GetProperty("Microseconds").GetGetMethod()) },
{ Unit.Nanoseconds, new UnitInfo<PrecisionTimeSpan>(UnitAbbreviations[Unit.Nanoseconds], FromNanoseconds, typeof(PrecisionTimeSpan).GetProperty("Nanoseconds").GetGetMethod()) }
};
internal const Decimal _nanoPerMicro = 1e3M;
internal const Decimal _nanoPerMilli = 1e6M;
internal const Decimal _nanoPerSec = 1e9M;
/// <summary>
/// Prevents a default instance of the <see cref="PrecisionTimeSpan"/> class from being created.
/// Use FromXXX methods to create objects of this type.
/// </summary>
/// <exception cref="System.Exception">No one should be calling this, it is only here to prevent users from creating default object</exception>
private PrecisionTimeSpan()
{
throw new InvalidOperationException("No one should be calling this, it is only here to prevent users from creating default object");
}
/// <summary>
/// ctor used by this class to create objects in FromXXX methods
/// </summary>
/// <param name="totalns">total number of nanoseconds.</param>
private PrecisionTimeSpan(Decimal totalns)
{
if (totalns < 0.0M)
throw new ArgumentOutOfRangeException("totalns", "Cannot create a negative timespan");
_totalns = totalns;
}
#region conversion properties
public double Nanoseconds
{
get { return (double)_totalns; }
}
public double Microseconds
{
get { return (double)(_totalns / _nanoPerMicro); }
}
public double Milliseconds
{
get { return (double)(_totalns / _nanoPerMilli); }
}
public double Seconds
{
get { return (double)(_totalns / _nanoPerSec); }
}
#endregion
#region creation methods
/// <summary>
/// Returns PrecisionTimeSpan object interpreting passed value as nanoseconds
/// </summary>
/// <param name="nanoseconds">total nanoseconds in the desired timespan</param>
/// <returns>the precision time span object</returns>
public static PrecisionTimeSpan FromNanoseconds(double nanoseconds)
{
return new PrecisionTimeSpan((Decimal)nanoseconds);
}
/// <summary>
/// Returns PrecisionTimeSpan object interpreting passed value as microseconds
/// </summary>
/// <param name="nanoseconds">total microseconds in the desired timespan</param>
/// <returns>the precision time span object</returns>
public static PrecisionTimeSpan FromMicroseconds(double microseconds)
{
return new PrecisionTimeSpan((Decimal)microseconds * _nanoPerMicro);
}
/// <summary>
/// Returns PrecisionTimeSpan object interpreting passed value as milliseconds
/// </summary>
/// <param name="nanoseconds">total milliseconds in the desired timespan</param>
/// <returns>the precision time span object</returns>
public static PrecisionTimeSpan FromMilliseconds(double milliseconds)
{
return new PrecisionTimeSpan((Decimal)milliseconds * _nanoPerMilli);
}
/// <summary>
/// Returns PrecisionTimeSpan object interpreting passed value as seconds
/// </summary>
/// <param name="nanoseconds">total seconds in the desired timespan</param>
/// <returns>the precision time span object</returns>
public static PrecisionTimeSpan FromSeconds(double seconds)
{
return new PrecisionTimeSpan((Decimal)seconds * _nanoPerSec);
}
#endregion
public override bool Equals(object obj)
{
PrecisionTimeSpan ts = obj as PrecisionTimeSpan;
return (ts == null) ? false : (this._totalns == ts._totalns);
}
public override int GetHashCode()
{
return _totalns.GetHashCode();
}
#region binary operators
// not implementing %, &, |, ^, <<, >>
public static PrecisionTimeSpan operator +(PrecisionTimeSpan left, PrecisionTimeSpan right)
{
if (null == left)
throw new ArgumentNullException("left", "Cannot add a null PrecisionTimeSpan");
if (null == right)
throw new ArgumentNullException("right", "Cannot add null PrecisionTimeSpan");
return new PrecisionTimeSpan(left._totalns + right._totalns);
}
public static PrecisionTimeSpan operator -(PrecisionTimeSpan left, PrecisionTimeSpan right)
{
if (null == left)
throw new ArgumentNullException("left", "Cannot subtract a null PrecisionTimeSpan");
if (null == right)
throw new ArgumentNullException("right", "Cannot subtract a null PrecisionTimeSpan");
if (right > left)
throw new ArgumentOutOfRangeException("right", "Cannot subtract a larger span from a smaller one");
return new PrecisionTimeSpan(left._totalns - right._totalns);
}
public static PrecisionTimeSpan operator *(PrecisionTimeSpan precisionTimeSpan, double scalar)
{
if (null == precisionTimeSpan)
throw new ArgumentNullException("precisionTimeSpan", "Cannot multiply a null PrecisionTimeSpan");
return new PrecisionTimeSpan(precisionTimeSpan._totalns * (Decimal)scalar);
}
public static PrecisionTimeSpan operator *(double scalar, PrecisionTimeSpan precisionTimeSpan)
{
if (null == precisionTimeSpan)
throw new ArgumentNullException("precisionTimeSpan", "Cannot multiply a null PrecisionTimeSpan");
return new PrecisionTimeSpan((Decimal)scalar * precisionTimeSpan._totalns);
}
public static PrecisionTimeSpan operator /(PrecisionTimeSpan precisionTimeSpan, double scalar)
{
if (null == precisionTimeSpan)
throw new ArgumentNullException("precisionTimeSpan", "Cannot divide a null PrecisionTimeSpan");
if (0.0 == scalar)
throw new DivideByZeroException("Cannot divide Precision Time Span by 0");
return new PrecisionTimeSpan(precisionTimeSpan._totalns / (Decimal)scalar);
}
#endregion
#region comparison operators
public static bool operator ==(PrecisionTimeSpan left, PrecisionTimeSpan right)
{
bool bReturn = false;
if (object.ReferenceEquals(left, null))
{
if (object.ReferenceEquals(right, null))
{
//both are null, so we are ==
bReturn = true;
}
}
else
{
if (!object.ReferenceEquals(left, null) &&
!object.ReferenceEquals(right, null))
{
bReturn = left._totalns == right._totalns;
}
}
return bReturn;
}
public static bool operator !=(PrecisionTimeSpan left, PrecisionTimeSpan right)
{
return !(left == right);
}
public static bool operator <(PrecisionTimeSpan left, PrecisionTimeSpan right)
{
if (null == left)
throw new ArgumentNullException("left", "Cannot compare null PrecisionTimeSpan");
if (null == right)
throw new ArgumentNullException("right", "Cannot compare null PrecisionTimeSpan");
return (left._totalns < right._totalns);
}
public static bool operator >(PrecisionTimeSpan left, PrecisionTimeSpan right)
{
if (null == left)
throw new ArgumentNullException("left", "Cannot compare null PrecisionTimeSpan");
if (null == right)
throw new ArgumentNullException("right", "Cannot compare null PrecisionTimeSpan");
return (left._totalns > right._totalns);
}
public static bool operator <=(PrecisionTimeSpan left, PrecisionTimeSpan right)
{
if (null == left)
throw new ArgumentNullException("left", "Cannot compare null PrecisionTimeSpan");
if (null == right)
throw new ArgumentNullException("right", "Cannot compare null PrecisionTimeSpan");
return (left._totalns <= right._totalns);
}
public static bool operator >=(PrecisionTimeSpan left, PrecisionTimeSpan right)
{
if (null == left)
throw new ArgumentNullException("left", "Cannot compare null PrecisionTimeSpan");
if (null == right)
throw new ArgumentNullException("right", "Cannot compare null PrecisionTimeSpan");
return (left._totalns >= right._totalns);
}
#endregion
#region operators with other classes
// no operators right now
#endregion
#region parsing
public static PrecisionTimeSpan Parse(string s)
{
return Common.Parse(s, _unitInfo);
}
public static bool TryParse(string s, out PrecisionTimeSpan value)
{
try
{
value = PrecisionTimeSpan.Parse(s);
return true;
}
catch (Exception)
{
value = null;
return false;
}
}
#endregion
/// <summary>
/// Returns a string appended with default units (e.g. "1.23 m/sec^2").
/// </summary>
/// <returns>
/// A string that represents this instance
/// </returns>
public override string ToString()
{
return ToString(DefaultUnits);
}
/// <summary>
/// overload that returns a string appended with specified units (e.g. "1.23 ft/sec^2").
/// </summary>
/// <param name="units"></param>
/// <returns></returns>
public string ToString(Unit units)
{
double value = (double)_unitInfo[units].PropertyGetter.Invoke(this, null);
return $"{value} {_unitInfo[units].Abbreviation[0]}";
}
}
}