|
| 1 | +using System; |
| 2 | +#if NET21_OR_GREATER |
| 3 | +using System.Runtime.CompilerServices; |
| 4 | +#endif |
| 5 | + |
| 6 | +namespace Renci.SshNet.Common |
| 7 | +{ |
| 8 | + /// <summary> |
| 9 | + /// Provides extension methods for <see cref="TimeSpan"/>. |
| 10 | + /// </summary> |
| 11 | + internal static class TimeSpanExtensions |
| 12 | + { |
| 13 | + /// <summary> |
| 14 | + /// Returns the specified <paramref name="timeSpan"/> as a valid timeout in milliseconds. |
| 15 | + /// </summary> |
| 16 | + /// <param name="timeSpan">The <see cref="TimeSpan"/> to ensure validity.</param> |
| 17 | + /// <param name="callerMemberName">The name of the calling member.</param> |
| 18 | + /// <exception cref="ArgumentOutOfRangeException"> |
| 19 | + /// Thrown when <paramref name="timeSpan"/> does not represent a value between -1 and <see cref="int.MaxValue"/>, inclusive. |
| 20 | + /// </exception> |
| 21 | + public static int AsTimeout(this TimeSpan timeSpan, |
| 22 | +#if NET21_OR_GREATER |
| 23 | + [CallerArgumentExpression(nameof(timeSpan))] |
| 24 | +#endif |
| 25 | + string callerMemberName = "") |
| 26 | + { |
| 27 | + var timeoutInMilliseconds = timeSpan.TotalMilliseconds; |
| 28 | + return timeoutInMilliseconds is < -1d or > int.MaxValue |
| 29 | + ? throw new ArgumentOutOfRangeException(callerMemberName, "The timeout must represent a value between -1 and Int32.MaxValue, inclusive.") |
| 30 | + : (int) timeoutInMilliseconds; |
| 31 | + } |
| 32 | + |
| 33 | + /// <summary> |
| 34 | + /// Ensures that the specified <paramref name="timeSpan"/> represents a valid timeout in milliseconds. |
| 35 | + /// </summary> |
| 36 | + /// <param name="timeSpan">The <see cref="TimeSpan"/> to ensure validity.</param> |
| 37 | + /// <param name="callerMemberName">The name of the calling member.</param> |
| 38 | + /// <exception cref="ArgumentOutOfRangeException"> |
| 39 | + /// Thrown when <paramref name="timeSpan"/> does not represent a value between -1 and <see cref="int.MaxValue"/>, inclusive. |
| 40 | + /// </exception> |
| 41 | + public static void EnsureValidTimeout(this TimeSpan timeSpan, |
| 42 | +#if NET21_OR_GREATER |
| 43 | + [CallerArgumentExpression(nameof(timeSpan))] |
| 44 | +#endif |
| 45 | + string callerMemberName = "") |
| 46 | + { |
| 47 | + var timeoutInMilliseconds = timeSpan.TotalMilliseconds; |
| 48 | + if (timeoutInMilliseconds is < -1d or > int.MaxValue) |
| 49 | + { |
| 50 | + throw new ArgumentOutOfRangeException(callerMemberName, "The timeout must represent a value between -1 and Int32.MaxValue, inclusive."); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments