Instantly share code, notes, and snippets.

Embed
What would you like to do?
JsBytes
use std::mem;
/// Struct that can be used to store a vector of bytes and sent
/// to JS
#[repr(C)]
#[derive(Debug)]
pub struct JsBytes {
ptr: u32,
len: u32,
}
impl JsBytes {
/// Create a new `JsBytes` wrapper consuming the bytes
pub fn new(mut bytes: Vec<u8>) -> *mut JsBytes {
bytes.shrink_to_fit();
let ptr = bytes.as_mut_ptr() as u32;
let len = bytes.len() as u32;
mem::forget(bytes);
let boxed = Box::new(JsBytes { ptr, len });
Box::into_raw(boxed)
}
/// Creates a `Vec` from a raw *mut JsBytes
pub unsafe fn from_raw(ptr: *mut JsBytes) -> Vec<u8> {
let boxed: Box<JsBytes> = Box::from_raw(ptr);
Vec::from_raw_parts(boxed.ptr as *mut u8, boxed.len as usize, boxed.len as usize)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment