TotallySafe
Overview
Welcome to TotallySafe, the Rust library that lets you boldly go where no safe code has gone
before-—all without a single unsafe block!
Features
- Arbitrary lifetimes: Get references with any lifetime you like. Who's to say what's 'correct'?
- Multiple Mutable References & Aliasing: Why settle for one mutable reference when you can have an array of them?
- Type Transmutation: Convert any type into any other type. After all, types are just labels.
- Fearless Copy: Byte-wise copy your objects without the need to implement
Clone and Copy.
Usage
Add totally_safe to your Cargo.toml:
[dependencies]
totally_safe = "0.1.0"
Bring the trait into scope:
use totally_safe::TotallySafe;
fn main() {
let mut value = Box::new(100);
let copied = value.copy();
}
API Documentation
Here's a closer look at what TotallySafe offers:
pub trait TotallySafe {
fn as_ref_alias<'x, 'any>(&'x self) -> &'any Self {
core::hint::black_box(
(((|inc, _| inc) as for<'a, 'b> fn(&'b Self, &'a &'b ()) -> &'a Self)
as for<'a, 'b> fn(&'x Self, &'a &'b ()) -> &'a Self)(self, &&()),
)
}
fn as_mut_alias<'x, 'any>(&'x mut self) -> &'any mut Self {
core::hint::black_box(
(((|inc, _| inc) as for<'a, 'b> fn(&'b mut Self, &'a &'b ()) -> &'a mut Self)
as for<'a, 'b> fn(&'x mut Self, &'a &'b ()) -> &'a mut Self)(self, &&()),
)
}
fn as_mut_alias_array<'x, 'any, const N: usize>(&'x mut self) -> [&'any mut Self; N]
where
Self: Sized,
{
core::array::from_fn(|_| self.as_mut_alias())
}
fn transmute_into<B>(self) -> B
where
Self: Sized,
{
core::hint::black_box({
let mut data = Err::<Option<Box<Self>>, Option<Box<B>>>(None);
let option_b = data.as_mut_alias().as_mut().err().unwrap();
*data.as_mut_alias() = Ok(Some(Box::new(self)));
*option_b.take().unwrap()
})
}
fn copy(&mut self) -> Self
where
Self: Sized,
{
core::hint::black_box(
*core::ptr::slice_from_raw_parts_mut(self, size_of_val(self))
.transmute_into::<&mut [u8]>()
.to_vec()
.into_boxed_slice()
.transmute_into::<Box<Self>>(),
)
}
}
License
You may use this library freely at your own risk, with no warranty, express or implied, and the authors are not liable for any damage or unintended consequences.