|
| 1 | +using System; |
| 2 | + |
| 3 | +namespace Renci.SshNet.Common |
| 4 | +{ |
| 5 | + /// <summary> |
| 6 | + /// Provides extension methods for <see cref="TimeSpan"/>. |
| 7 | + /// </summary> |
| 8 | + internal static class TimeSpanExtensions |
| 9 | + { |
| 10 | + private const string OutOfRangeTimeoutMessage = |
| 11 | + $"The timeout must represent a value between -1 and Int32.MaxValue milliseconds, inclusive."; |
| 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, string callerMemberName) |
| 22 | + { |
| 23 | + var timeoutInMilliseconds = timeSpan.TotalMilliseconds; |
| 24 | + return timeoutInMilliseconds is < -1d or > int.MaxValue |
| 25 | + ? throw new ArgumentOutOfRangeException(callerMemberName, OutOfRangeTimeoutMessage) |
| 26 | + : (int) timeoutInMilliseconds; |
| 27 | + } |
| 28 | + |
| 29 | + /// <summary> |
| 30 | + /// Ensures that the specified <paramref name="timeSpan"/> represents a valid timeout in milliseconds. |
| 31 | + /// </summary> |
| 32 | + /// <param name="timeSpan">The <see cref="TimeSpan"/> to ensure validity.</param> |
| 33 | + /// <param name="callerMemberName">The name of the calling member.</param> |
| 34 | + /// <exception cref="ArgumentOutOfRangeException"> |
| 35 | + /// Thrown when <paramref name="timeSpan"/> does not represent a value between -1 and <see cref="int.MaxValue"/>, inclusive. |
| 36 | + /// </exception> |
| 37 | + public static void EnsureValidTimeout(this TimeSpan timeSpan, string callerMemberName) |
| 38 | + { |
| 39 | + var timeoutInMilliseconds = timeSpan.TotalMilliseconds; |
| 40 | + if (timeoutInMilliseconds is < -1d or > int.MaxValue) |
| 41 | + { |
| 42 | + throw new ArgumentOutOfRangeException(callerMemberName, OutOfRangeTimeoutMessage); |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | +} |
0 commit comments