using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace Raytheon.Units { /// /// 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 /// [Serializable] [DataContract] public class PrecisionTimeSpan { public enum Unit { Seconds, Milliseconds, Microseconds, Nanoseconds } public static IDictionary> UnitAbbreviations = new Dictionary>() { {Unit.Seconds, new List(){ "sec" } }, {Unit.Milliseconds, new List(){ "msec" } }, {Unit.Microseconds, new List(){ "usec" } }, {Unit.Nanoseconds, new List(){ "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> _unitInfo = new Dictionary>() { { Unit.Seconds, new UnitInfo(UnitAbbreviations[Unit.Seconds], FromSeconds, typeof(PrecisionTimeSpan).GetProperty("Seconds").GetGetMethod()) }, { Unit.Milliseconds, new UnitInfo(UnitAbbreviations[Unit.Milliseconds], FromMilliseconds, typeof(PrecisionTimeSpan).GetProperty("Milliseconds").GetGetMethod()) }, { Unit.Microseconds, new UnitInfo(UnitAbbreviations[Unit.Microseconds], FromMicroseconds, typeof(PrecisionTimeSpan).GetProperty("Microseconds").GetGetMethod()) }, { Unit.Nanoseconds, new UnitInfo(UnitAbbreviations[Unit.Nanoseconds], FromNanoseconds, typeof(PrecisionTimeSpan).GetProperty("Nanoseconds").GetGetMethod()) } }; internal const Decimal _nanoPerMicro = 1e3M; internal const Decimal _nanoPerMilli = 1e6M; internal const Decimal _nanoPerSec = 1e9M; /// /// Prevents a default instance of the class from being created. /// Use FromXXX methods to create objects of this type. /// /// No one should be calling this, it is only here to prevent users from creating default object private PrecisionTimeSpan() { throw new InvalidOperationException("No one should be calling this, it is only here to prevent users from creating default object"); } /// /// ctor used by this class to create objects in FromXXX methods /// /// total number of nanoseconds. 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 /// /// Returns PrecisionTimeSpan object interpreting passed value as nanoseconds /// /// total nanoseconds in the desired timespan /// the precision time span object public static PrecisionTimeSpan FromNanoseconds(double nanoseconds) { return new PrecisionTimeSpan((Decimal)nanoseconds); } /// /// Returns PrecisionTimeSpan object interpreting passed value as microseconds /// /// total microseconds in the desired timespan /// the precision time span object public static PrecisionTimeSpan FromMicroseconds(double microseconds) { return new PrecisionTimeSpan((Decimal)microseconds * _nanoPerMicro); } /// /// Returns PrecisionTimeSpan object interpreting passed value as milliseconds /// /// total milliseconds in the desired timespan /// the precision time span object public static PrecisionTimeSpan FromMilliseconds(double milliseconds) { return new PrecisionTimeSpan((Decimal)milliseconds * _nanoPerMilli); } /// /// Returns PrecisionTimeSpan object interpreting passed value as seconds /// /// total seconds in the desired timespan /// the precision time span object 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 /// /// Returns a string appended with default units (e.g. "1.23 m/sec^2"). /// /// /// A string that represents this instance /// public override string ToString() { return ToString(DefaultUnits); } /// /// overload that returns a string appended with specified units (e.g. "1.23 ft/sec^2"). /// /// /// public string ToString(Unit units) { double value = (double)_unitInfo[units].PropertyGetter.Invoke(this, null); return $"{value} {_unitInfo[units].Abbreviation[0]}"; } } }