Timespec.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. #region Copyright notice and license
  2. // Copyright 2015 gRPC authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #endregion
  16. using System;
  17. using System.Runtime.InteropServices;
  18. using System.Threading;
  19. using Grpc.Core.Utils;
  20. namespace Grpc.Core.Internal
  21. {
  22. /// <summary>
  23. /// gpr_timespec from grpc/support/time.h
  24. /// </summary>
  25. [StructLayout(LayoutKind.Sequential)]
  26. internal struct Timespec : IEquatable<Timespec>
  27. {
  28. /// <summary>
  29. /// Indicates whether this instance and a specified object are equal.
  30. /// </summary>
  31. public override bool Equals(object obj)
  32. {
  33. return obj is Timespec && Equals((Timespec)obj);
  34. }
  35. /// <summary>
  36. /// Returns the hash code for this instance.
  37. /// </summary>
  38. public override int GetHashCode()
  39. {
  40. unchecked
  41. {
  42. const int Prime = 373587911;
  43. int i = (int)clock_type;
  44. i = (i * Prime) ^ tv_nsec;
  45. i = (i * Prime) ^ tv_nsec.GetHashCode();
  46. return i;
  47. }
  48. }
  49. /// <summary>
  50. /// Returns the full type name of this instance.
  51. /// </summary>
  52. public override string ToString()
  53. {
  54. return typeof(Timespec).FullName;
  55. }
  56. /// <summary>
  57. /// Indicates whether this instance and a specified object are equal.
  58. /// </summary>
  59. public bool Equals(Timespec other)
  60. {
  61. return this.clock_type == other.clock_type
  62. && this.tv_nsec == other.tv_nsec
  63. && this.tv_sec == other.tv_sec;
  64. }
  65. const long NanosPerSecond = 1000 * 1000 * 1000;
  66. const long NanosPerTick = 100;
  67. const long TicksPerSecond = NanosPerSecond / NanosPerTick;
  68. static readonly NativeMethods Native = NativeMethods.Get();
  69. static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  70. public Timespec(long tv_sec, int tv_nsec) : this(tv_sec, tv_nsec, ClockType.Realtime)
  71. {
  72. }
  73. public Timespec(long tv_sec, int tv_nsec, ClockType clock_type)
  74. {
  75. this.tv_sec = tv_sec;
  76. this.tv_nsec = tv_nsec;
  77. this.clock_type = clock_type;
  78. }
  79. private long tv_sec;
  80. private int tv_nsec;
  81. private ClockType clock_type;
  82. /// <summary>
  83. /// Timespec a long time in the future.
  84. /// </summary>
  85. public static Timespec InfFuture
  86. {
  87. get
  88. {
  89. return new Timespec(long.MaxValue, 0, ClockType.Realtime);
  90. }
  91. }
  92. /// <summary>
  93. /// Timespec a long time in the past.
  94. /// </summary>
  95. public static Timespec InfPast
  96. {
  97. get
  98. {
  99. return new Timespec(long.MinValue, 0, ClockType.Realtime);
  100. }
  101. }
  102. /// <summary>
  103. /// Return Timespec representing the current time.
  104. /// </summary>
  105. public static Timespec Now
  106. {
  107. get
  108. {
  109. return Native.gprsharp_now(ClockType.Realtime);
  110. }
  111. }
  112. /// <summary>
  113. /// Seconds since unix epoch.
  114. /// </summary>
  115. public long TimevalSeconds
  116. {
  117. get
  118. {
  119. return tv_sec;
  120. }
  121. }
  122. /// <summary>
  123. /// The nanoseconds part of timeval.
  124. /// </summary>
  125. public int TimevalNanos
  126. {
  127. get
  128. {
  129. return tv_nsec;
  130. }
  131. }
  132. /// <summary>
  133. /// Converts the timespec to desired clock type.
  134. /// </summary>
  135. public Timespec ToClockType(ClockType targetClock)
  136. {
  137. return Native.gprsharp_convert_clock_type(this, targetClock);
  138. }
  139. /// <summary>
  140. /// Converts Timespec to DateTime.
  141. /// Timespec needs to be of type GPRClockType.Realtime and needs to represent a legal value.
  142. /// DateTime has lower resolution (100ns), so rounding can occurs.
  143. /// Value are always rounded up to the nearest DateTime value in the future.
  144. ///
  145. /// For Timespec.InfFuture or if timespec is after the largest representable DateTime, DateTime.MaxValue is returned.
  146. /// For Timespec.InfPast or if timespec is before the lowest representable DateTime, DateTime.MinValue is returned.
  147. ///
  148. /// Unless DateTime.MaxValue or DateTime.MinValue is returned, the resulting DateTime is always in UTC
  149. /// (DateTimeKind.Utc)
  150. /// </summary>
  151. public DateTime ToDateTime()
  152. {
  153. GrpcPreconditions.CheckState(tv_nsec >= 0 && tv_nsec < NanosPerSecond);
  154. GrpcPreconditions.CheckState(clock_type == ClockType.Realtime);
  155. // fast path for InfFuture
  156. if (this.Equals(InfFuture))
  157. {
  158. return DateTime.MaxValue;
  159. }
  160. // fast path for InfPast
  161. if (this.Equals(InfPast))
  162. {
  163. return DateTime.MinValue;
  164. }
  165. try
  166. {
  167. // convert nanos to ticks, round up to the nearest tick
  168. long ticksFromNanos = tv_nsec / NanosPerTick + ((tv_nsec % NanosPerTick != 0) ? 1 : 0);
  169. long ticksTotal = checked(tv_sec * TicksPerSecond + ticksFromNanos);
  170. return UnixEpoch.AddTicks(ticksTotal);
  171. }
  172. catch (OverflowException)
  173. {
  174. // ticks out of long range
  175. return tv_sec > 0 ? DateTime.MaxValue : DateTime.MinValue;
  176. }
  177. catch (ArgumentOutOfRangeException)
  178. {
  179. // resulting date time would be larger than MaxValue
  180. return tv_sec > 0 ? DateTime.MaxValue : DateTime.MinValue;
  181. }
  182. }
  183. /// <summary>
  184. /// Creates DateTime to Timespec.
  185. /// DateTime has to be in UTC (DateTimeKind.Utc) unless it's DateTime.MaxValue or DateTime.MinValue.
  186. /// For DateTime.MaxValue of date time after the largest representable Timespec, Timespec.InfFuture is returned.
  187. /// For DateTime.MinValue of date time before the lowest representable Timespec, Timespec.InfPast is returned.
  188. /// </summary>
  189. /// <returns>The date time.</returns>
  190. /// <param name="dateTime">Date time.</param>
  191. public static Timespec FromDateTime(DateTime dateTime)
  192. {
  193. if (dateTime == DateTime.MaxValue)
  194. {
  195. return Timespec.InfFuture;
  196. }
  197. if (dateTime == DateTime.MinValue)
  198. {
  199. return Timespec.InfPast;
  200. }
  201. GrpcPreconditions.CheckArgument(dateTime.Kind == DateTimeKind.Utc, "dateTime needs of kind DateTimeKind.Utc or be equal to DateTime.MaxValue or DateTime.MinValue.");
  202. try
  203. {
  204. TimeSpan timeSpan = dateTime - UnixEpoch;
  205. long ticks = timeSpan.Ticks;
  206. long seconds = ticks / TicksPerSecond;
  207. int nanos = (int)((ticks % TicksPerSecond) * NanosPerTick);
  208. if (nanos < 0)
  209. {
  210. // correct the result based on C# modulo semantics for negative dividend
  211. seconds--;
  212. nanos += (int)NanosPerSecond;
  213. }
  214. return new Timespec(seconds, nanos);
  215. }
  216. catch (ArgumentOutOfRangeException)
  217. {
  218. return dateTime > UnixEpoch ? Timespec.InfFuture : Timespec.InfPast;
  219. }
  220. }
  221. /// <summary>
  222. /// Gets current timestamp using <c>GPRClockType.Precise</c>.
  223. /// Only available internally because core needs to be compiled with
  224. /// GRPC_TIMERS_RDTSC support for this to use RDTSC.
  225. /// </summary>
  226. internal static Timespec PreciseNow
  227. {
  228. get
  229. {
  230. return Native.gprsharp_now(ClockType.Precise);
  231. }
  232. }
  233. // for tests only
  234. internal static int NativeSize
  235. {
  236. get
  237. {
  238. return Native.gprsharp_sizeof_timespec();
  239. }
  240. }
  241. // for tests only
  242. internal static Timespec NativeInfFuture
  243. {
  244. get
  245. {
  246. return Native.gprsharp_inf_future(ClockType.Realtime);
  247. }
  248. }
  249. // for tests only
  250. public static Timespec NativeInfPast
  251. {
  252. get
  253. {
  254. return Native.gprsharp_inf_past(ClockType.Realtime);
  255. }
  256. }
  257. }
  258. }