Skip to content

Instantly share code, notes, and snippets.

@yuri91
Last active June 14, 2018 15:56
Show Gist options
  • Save yuri91/8a671fc77129230f86ad7bae844221c8 to your computer and use it in GitHub Desktop.
Save yuri91/8a671fc77129230f86ad7bae844221c8 to your computer and use it in GitHub Desktop.
interop blog post 1
/// Allocate space for a mappings string of the given size (in bytes).
///
/// It is the JS callers responsibility to initialize the resulting buffer by
/// copying the JS `String` holding the source map's "mappings" into it (encoded
/// in ascii).
#[no_mangle]
pub extern "C" fn allocate_mappings(size: usize) -> *mut u8 {
// Make sure that we don't lose any bytes from size in the remainder.
let size_in_units_of_usize = (size + mem::size_of::<usize>() - 1) / mem::size_of::<usize>();
// Make room for two additional `usize`s: we'll stuff capacity and length in
// there.
let mut vec: Vec<usize> = Vec::with_capacity(size_in_units_of_usize + 2);
// And do the stuffing.
let capacity = vec.capacity();
vec.push(capacity);
vec.push(size);
// Leak the vec's elements and get a pointer to them.
let ptr = vec.as_mut_ptr();
debug_assert!(!ptr.is_null());
mem::forget(vec);
// Advance the pointer past our stuffed data and return it to JS, so that JS
// can write the mappings string into it.
let ptr = ptr.wrapping_offset(2) as *mut u8;
assert_pointer_is_word_aligned(ptr);
ptr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment