Skip to main content

web_transport_trait/
util.rs

1//! Initialized buffers and utility traits for conditional Send/Sync bounds.
2//!
3//! These traits allow the same code to work on both native and WASM targets,
4//! where WASM doesn't support Send/Sync.
5
6pub(crate) const READ_CAPACITY: usize = 8 * 1024;
7
8/// Initialize spare capacity before exposing it to a safe reader.
9pub(crate) fn initialize(dst: &mut bytes::buf::UninitSlice) -> &mut [u8] {
10    // Bound initialization independently of allocation size and read progress.
11    let len = dst.len().min(READ_CAPACITY);
12    let dst = &mut dst[..len];
13    for index in 0..dst.len() {
14        dst.write_byte(index, 0);
15    }
16
17    // SAFETY: Every byte was initialized above, and the slice retains the
18    // exclusive borrow and bounds of the original destination.
19    unsafe { std::slice::from_raw_parts_mut(dst.as_mut_ptr(), dst.len()) }
20}
21
22/// A trait that is Send on native targets and empty on WASM.
23#[cfg(not(target_family = "wasm"))]
24pub trait MaybeSend: Send {}
25
26/// A trait that is Sync on native targets and empty on WASM.
27#[cfg(not(target_family = "wasm"))]
28pub trait MaybeSync: Sync {}
29
30#[cfg(not(target_family = "wasm"))]
31impl<T: Send> MaybeSend for T {}
32
33#[cfg(not(target_family = "wasm"))]
34impl<T: Sync> MaybeSync for T {}
35
36/// A trait that is Send on native targets and empty on WASM.
37#[cfg(target_family = "wasm")]
38pub trait MaybeSend {}
39
40/// A trait that is Sync on native targets and empty on WASM.
41#[cfg(target_family = "wasm")]
42pub trait MaybeSync {}
43
44#[cfg(target_family = "wasm")]
45impl<T> MaybeSend for T {}
46
47#[cfg(target_family = "wasm")]
48impl<T> MaybeSync for T {}