Skip to main content

pawkit_net/
lib.rs

1mod client;
2mod host;
3
4use std::{future::Future, sync::LazyLock};
5
6pub use pawkit_net_signaling as signaling;
7
8pub use client::*;
9use futures_util::{FutureExt, future::select_all};
10pub use host::*;
11use just_webrtc::{
12    DataChannelExt, PeerConnectionExt,
13    platform::{Channel, PeerConnection},
14};
15use tokio::runtime::Runtime;
16
17#[cfg(not(target_arch = "wasm32"))]
18type PacketFuture = dyn Future<Output = (Option<(usize, Vec<u8>)>, usize)> + Send + Sync;
19#[cfg(target_arch = "wasm32")]
20type PacketFuture = dyn Future<Output = (Option<(usize, Vec<u8>)>, usize)>;
21
22static RUNTIME: LazyLock<Runtime> = LazyLock::new(|| Runtime::new().unwrap());
23
24struct Connection {
25    pub raw_connection: PeerConnection,
26    pub channels: Box<[Channel]>,
27}
28
29impl Connection {
30    pub async fn from(
31        raw_connection: PeerConnection,
32        channels: usize,
33    ) -> Result<Self, just_webrtc::platform::Error> {
34        let mut c = vec![];
35
36        for _ in 0..channels {
37            c.push(raw_connection.receive_channel().await?);
38        }
39
40        return Ok(Self {
41            channels: c.into_boxed_slice(),
42            raw_connection,
43        });
44    }
45}
46
47async fn receive_packet(channel: &Channel) -> Option<Vec<u8>> {
48    return channel.receive().await.map(|it| it.to_vec()).ok();
49}
50
51async fn receive_packets(channels: &[Channel]) -> Option<(usize, Vec<u8>)> {
52    let futures = channels.iter().map(|ch| receive_packet(ch).boxed());
53
54    let (result, idx, _remaining) = select_all(futures).await;
55
56    result.map(|data| (idx, data))
57}