Guest User

Untitled

a guest
Oct 21st, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. use std::mem;
  2.  
  3. /// Struct that can be used to store a vector of bytes and sent
  4. /// to JS
  5. #[repr(C)]
  6. #[derive(Debug)]
  7. pub struct JsBytes {
  8. ptr: u32,
  9. len: u32,
  10. }
  11.  
  12. impl JsBytes {
  13. /// Create a new `JsBytes` wrapper consuming the bytes
  14. pub fn new(mut bytes: Vec<u8>) -> *mut JsBytes {
  15. bytes.shrink_to_fit();
  16. let ptr = bytes.as_mut_ptr() as u32;
  17. let len = bytes.len() as u32;
  18. mem::forget(bytes);
  19. let boxed = Box::new(JsBytes { ptr, len });
  20. Box::into_raw(boxed)
  21. }
  22.  
  23. /// Creates a `Vec` from a raw *mut JsBytes
  24. pub unsafe fn from_raw(ptr: *mut JsBytes) -> Vec<u8> {
  25. let boxed: Box<JsBytes> = Box::from_raw(ptr);
  26. Vec::from_raw_parts(boxed.ptr as *mut u8, boxed.len as usize, boxed.len as usize)
  27. }
  28. }
Add Comment
Please, Sign In to add comment