Skip to content

Instantly share code, notes, and snippets.

@DutchGhost
Last active August 23, 2021 15:20
Show Gist options
  • Save DutchGhost/2ca9c8dd152bc3444db4354da04ac715 to your computer and use it in GitHub Desktop.
Save DutchGhost/2ca9c8dd152bc3444db4354da04ac715 to your computer and use it in GitHub Desktop.
#![allow(incomplete_features)]
#![feature(
const_trait_impl,
const_fn_trait_bound,
const_generics,
const_evaluatable_checked,
specialization
)]
use core::mem::ManuallyDrop;
union ByteType<T: Sized>
where
[(); core::mem::size_of::<T>()]: ,
{
t: core::mem::ManuallyDrop<T>,
bytes: [u8; core::mem::size_of::<T>()],
}
impl<T: Sized> ByteType<T>
where
[(); core::mem::size_of::<T>()]: ,
{
pub const fn new(value: T) -> Self {
Self {
t: core::mem::ManuallyDrop::new(value),
}
}
pub const unsafe fn from_bytes(bytes: [u8; core::mem::size_of::<T>()]) -> Self {
Self { bytes }
}
pub const fn as_bytes(&self) -> &[u8] {
unsafe { &self.bytes }
}
pub const fn as_array(self) -> [u8; core::mem::size_of::<T>()] {
let bytes = unsafe { self.bytes };
core::mem::forget(self);
bytes
}
}
impl<T: Sized> core::ops::Deref for ByteType<T>
where
[(); core::mem::size_of::<T>()]: ,
{
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { &self.t }
}
}
impl<T: Sized> core::ops::DerefMut for ByteType<T>
where
[(); core::mem::size_of::<T>()]: ,
{
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut self.t }
}
}
impl<T: Sized> Drop for ByteType<T>
where
[(); core::mem::size_of::<T>()]: ,
{
fn drop(&mut self) {
unsafe { ManuallyDrop::drop(&mut self.t) }
}
}
fn main() {
let mut x = ByteType::new(Vec::<i32>::new());
dbg!(x.as_bytes());
x.push(1);
// dbg!(x.as_bytes());
let b = x.as_array();
let mut x = unsafe { ByteType::<Vec<u32>>::from_bytes(b) };
x.push(1);
// dbg!(x.as_bytes());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment