| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | |
| | | 6 | | namespace System.Net.WebSockets |
| | | 7 | | { |
| | | 8 | | internal static class WebSocketStateHelper |
| | | 9 | | { |
| | | 10 | | /// <summary>Valid states to be in when calling SendAsync.</summary> |
| | | 11 | | internal const ManagedWebSocketStates ValidSendStates = ManagedWebSocketStates.Open | ManagedWebSocketStates.Clo |
| | | 12 | | /// <summary>Valid states to be in when calling ReceiveAsync.</summary> |
| | | 13 | | internal const ManagedWebSocketStates ValidReceiveStates = ManagedWebSocketStates.Open | ManagedWebSocketStates. |
| | | 14 | | /// <summary>Valid states to be in when calling CloseOutputAsync.</summary> |
| | | 15 | | internal const ManagedWebSocketStates ValidCloseOutputStates = ManagedWebSocketStates.Open | ManagedWebSocketSta |
| | | 16 | | /// <summary>Valid states to be in when calling CloseAsync.</summary> |
| | | 17 | | internal const ManagedWebSocketStates ValidCloseStates = ManagedWebSocketStates.Open | ManagedWebSocketStates.Cl |
| | | 18 | | |
| | 0 | 19 | | internal static bool IsValidSendState(WebSocketState state) => (ValidSendStates & ToFlag(state)) != 0; |
| | | 20 | | |
| | | 21 | | internal static void ThrowIfInvalidState(WebSocketState currentState, bool isDisposed, Exception? innerException |
| | 415390 | 22 | | { |
| | 415390 | 23 | | ManagedWebSocketStates state = ToFlag(currentState); |
| | | 24 | | |
| | 415390 | 25 | | if ((state & validStates) == 0) |
| | 99 | 26 | | { |
| | 99 | 27 | | string invalidStateMessage = SR.Format( |
| | 99 | 28 | | SR.net_WebSockets_InvalidState, currentState, validStates); |
| | | 29 | | |
| | 99 | 30 | | throw new WebSocketException(WebSocketError.InvalidState, invalidStateMessage, innerException); |
| | | 31 | | } |
| | | 32 | | |
| | 415291 | 33 | | if (innerException is not null) |
| | 0 | 34 | | { |
| | 0 | 35 | | Debug.Assert(state == ManagedWebSocketStates.Aborted); |
| | 0 | 36 | | throw new OperationCanceledException(nameof(WebSocketState.Aborted), innerException); |
| | | 37 | | } |
| | | 38 | | |
| | | 39 | | // Ordering is important to maintain .NET 4.5 WebSocket implementation exception behavior. |
| | 415291 | 40 | | ObjectDisposedException.ThrowIf(isDisposed, typeof(WebSocket)); |
| | 415291 | 41 | | } |
| | | 42 | | |
| | | 43 | | private static ManagedWebSocketStates ToFlag(WebSocketState value) |
| | 415390 | 44 | | { |
| | 415390 | 45 | | ManagedWebSocketStates flag = (ManagedWebSocketStates)(1 << (int)value); |
| | 415390 | 46 | | Debug.Assert(Enum.IsDefined(flag)); |
| | 415390 | 47 | | return flag; |
| | 415390 | 48 | | } |
| | | 49 | | } |
| | | 50 | | } |
| | | 51 | | |