Better feature locking, add wasm.rs

This commit is contained in:
bitfl0wer 2023-11-19 22:04:18 +01:00
parent 73342d5dd7
commit 8f0d8813eb
2 changed files with 63 additions and 4 deletions

View File

@ -1,9 +1,22 @@
#[cfg(not(target_arch = "wasm32"))] #[cfg(all(not(target_arch = "wasm32"), feature = "client"))]
pub mod tungstenite; pub mod tungstenite;
#[cfg(all(not(target_arch = "wasm32"), feature = "client"))]
pub use tungstenite::*;
#[cfg(all(target_arch = "wasm32", feature = "client"))]
pub mod wasm;
#[cfg(all(target_arch = "wasm32", feature = "client"))]
pub use wasm::*;
#[cfg(not(target_arch = "wasm32"))] #[cfg(all(not(target_arch = "wasm32"), feature = "client"))]
pub type Sink = tungstenite::TungsteniteSink; pub type Sink = tungstenite::TungsteniteSink;
#[cfg(not(target_arch = "wasm32"))] #[cfg(all(not(target_arch = "wasm32"), feature = "client"))]
pub type Stream = tungstenite::TungsteniteStream; pub type Stream = tungstenite::TungsteniteStream;
#[cfg(not(target_arch = "wasm32"))] #[cfg(all(not(target_arch = "wasm32"), feature = "client"))]
pub type WebSocketBackend = tungstenite::TungsteniteBackend; pub type WebSocketBackend = tungstenite::TungsteniteBackend;
#[cfg(all(target_arch = "wasm32", feature = "client"))]
pub type Sink = wasm::WasmSink;
#[cfg(all(target_arch = "wasm32", feature = "client"))]
pub type Stream = wasm::WasmStream;
#[cfg(all(target_arch = "wasm32", feature = "client"))]
pub type WebSocketBackend = wasm::WasmBackend;

View File

@ -0,0 +1,46 @@
use futures_util::{
stream::{SplitSink, SplitStream},
StreamExt,
};
use ws_stream_wasm::*;
use crate::errors::GatewayError;
use crate::gateway::GatewayMessage;
#[derive(Debug, Clone)]
pub struct WasmBackend;
// These could be made into inherent associated types when that's stabilized
pub type WasmSink = SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, tungstenite::Message>;
pub type WasmStream = SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>;
impl WasmBackend {
pub async fn connect(
websocket_url: &str,
) -> Result<(WasmSink, WasmStream), crate::errors::GatewayError> {
let (websocket_stream, _) = match WsMeta::connect();
{
Ok(websocket_stream) => websocket_stream,
Err(e) => {
return Err(GatewayError::CannotConnect {
error: e.to_string(),
})
}
};
Ok(websocket_stream.split())
}
}
impl From<GatewayMessage> for WsMessage {
fn from(message: GatewayMessage) -> Self {
Self::Text(message.0)
}
}
impl From<WsMessage> for GatewayMessage {
fn from(value: WsMessage) -> Self {
Self(value.to_string())
}
}