random small things:

Send wrapper
available_parallelism
This commit is contained in:
Janis 2025-07-02 18:07:25 +02:00
parent 2fabc61378
commit 119b49e20d
2 changed files with 50 additions and 6 deletions

View file

@ -11,10 +11,6 @@ pub mod drop_guard;
pub mod ptr;
#[cfg(feature = "alloc")]
pub mod smallbox;
pub mod util;
pub const fn can_transmute<A, B>() -> bool {
use core::mem::{align_of, size_of};
// We can transmute `A` to `B` iff `A` and `B` have the same size and the
// alignment of `A` is greater than or equal to the alignment of `B`.
size_of::<A>() <= size_of::<B>() && align_of::<A>() >= align_of::<B>()
}
pub use util::can_transmute;

48
src/util.rs Normal file
View file

@ -0,0 +1,48 @@
use core::ops::{Deref, DerefMut};
#[repr(transparent)]
pub struct Send<T>(pub(self) T);
unsafe impl<T> core::marker::Send for Send<T> {}
impl<T> Deref for Send<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for Send<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T> Send<T> {
pub unsafe fn new(value: T) -> Self {
Self(value)
}
}
/// returns the number of available hardware threads, or 1 if it cannot be determined.
#[cfg(feature = "std")]
pub fn available_parallelism() -> usize {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
}
#[cfg(feature = "std")]
pub fn unwrap_or_panic<T>(result: std::thread::Result<T>) -> T {
match result {
Ok(value) => value,
Err(payload) => std::panic::resume_unwind(payload),
}
}
pub const fn can_transmute<A, B>() -> bool {
use core::mem::{align_of, size_of};
// We can transmute `A` to `B` iff `A` and `B` have the same size and the
// alignment of `A` is greater than or equal to the alignment of `B`.
size_of::<A>() <= size_of::<B>() && align_of::<A>() >= align_of::<B>()
}