#[cfg(feature = "i_like_breaking_production")]
use std::{io::{Write, Read}, path::Path};
#[cfg(feature = "i_like_breaking_production")]
use tempfile::Builder;
#[cfg(feature = "i_like_breaking_production")]
pub struct MemPickle {
file: tempfile::NamedTempFile,
}
#[cfg(feature = "i_like_breaking_production")]
impl MemPickle {
pub fn new<T>(data: T) -> Result<Self, std::io::Error> {
let ptr = &data as *const T as *const u8;
let len = std::mem::size_of::<T>();
let data = unsafe { std::slice::from_raw_parts(ptr, len) };
let file = Builder::new()
.prefix("tmp_pickle")
.suffix(".pickle")
.tempfile()?;
file.as_file().write_all(data)?;
Ok(Self { file })
}
pub fn path(&self) -> &Path {
self.file.path()
}
pub fn unwrap<T>(self) -> Result<T, std::io::Error> {
let mut file = self.file;
let mut data = Vec::new();
file.read_to_end(&mut data)?;
drop(file);
let data: T = *unsafe { Box::from_raw(data.as_ptr() as *mut T) };
Ok(data)
}
}
#[cfg(feature = "i_like_breaking_production")]
impl Drop for MemPickle {
fn drop(&mut self) {
let _ = self.file.close();
}
}