Skip to content

Instantly share code, notes, and snippets.

@thomas-jeepe
Created October 20, 2017 18:48
Show Gist options
  • Save thomas-jeepe/5e00071c10a87c62b02aeca1f36f03b1 to your computer and use it in GitHub Desktop.
Save thomas-jeepe/5e00071c10a87c62b02aeca1f36f03b1 to your computer and use it in GitHub Desktop.
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