wasm_ws/
state.rs

1// Copyright (c) 2019-2022 Naja Melan
2// Copyright (c) 2023-2024 Yuki Kishimoto
3// Distributed under the MIT software license
4
5use web_sys::WebSocket;
6
7use crate::WsErr;
8
9/// Indicates the state of a Websocket connection. The only state in which it's valid to send and receive messages
10/// is [WsState::Open].
11///
12/// See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState) for the ready state values.
13#[allow(missing_docs)]
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum WsState {
16    Connecting,
17    Open,
18    Closing,
19    Closed,
20}
21
22/// Internally ready state is a u16, so it's possible to create one from a u16. Only 0-3 are valid values.
23///
24/// See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState) for the ready state values.
25impl TryFrom<u16> for WsState {
26    type Error = WsErr;
27
28    fn try_from(state: u16) -> Result<Self, Self::Error> {
29        match state {
30            WebSocket::CONNECTING => Ok(WsState::Connecting),
31            WebSocket::OPEN => Ok(WsState::Open),
32            WebSocket::CLOSING => Ok(WsState::Closing),
33            WebSocket::CLOSED => Ok(WsState::Closed),
34            _ => Err(WsErr::InvalidWsState { supplied: state }),
35        }
36    }
37}