zed/crates/plugin/src/lib.rs

62 lines
1.6 KiB
Rust
Raw Normal View History

pub use bincode;
pub use serde;
/// This is the buffer that is used Wasm side.
/// Note that it mirrors the functionality of
/// the `WasiBuffer` found in `plugin_runtime/src/plugin.rs`,
/// But has a few different methods.
2022-06-03 09:18:54 +00:00
pub struct __Buffer {
pub ptr: u32, // *const u8,
pub len: u32, // usize,
}
impl __Buffer {
pub fn into_u64(self) -> u64 {
((self.ptr as u64) << 32) | (self.len as u64)
}
pub fn from_u64(packed: u64) -> Self {
__Buffer {
ptr: (packed >> 32) as u32,
len: packed as u32,
}
}
2022-06-02 15:49:02 +00:00
}
/// Allocates a buffer with an exact size.
/// We don't return the size because it has to be passed in anyway.
#[no_mangle]
pub extern "C" fn __alloc_buffer(len: u32) -> u32 {
let vec = vec![0; len as usize];
2022-06-03 09:18:54 +00:00
let buffer = unsafe { __Buffer::from_vec(vec) };
buffer.ptr
2022-06-02 15:49:02 +00:00
}
/// Frees a given buffer, requires the size.
#[no_mangle]
pub extern "C" fn __free_buffer(buffer: u64) {
let vec = unsafe { __Buffer::from_u64(buffer).to_vec() };
std::mem::drop(vec);
}
2022-06-02 15:49:02 +00:00
2022-06-03 09:18:54 +00:00
impl __Buffer {
#[inline(always)]
2022-06-02 15:49:02 +00:00
pub unsafe fn to_vec(&self) -> Vec<u8> {
core::slice::from_raw_parts(self.ptr as *const u8, self.len as usize).to_vec()
2022-06-02 15:49:02 +00:00
}
#[inline(always)]
2022-06-03 09:18:54 +00:00
pub unsafe fn from_vec(mut vec: Vec<u8>) -> __Buffer {
2022-06-02 15:49:02 +00:00
vec.shrink_to(0);
let ptr = vec.as_ptr() as u32;
let len = vec.len() as u32;
2022-06-02 15:49:02 +00:00
std::mem::forget(vec);
2022-06-03 09:18:54 +00:00
__Buffer { ptr, len }
2022-06-02 15:49:02 +00:00
}
}
pub mod prelude {
2022-06-03 09:18:54 +00:00
pub use super::{__Buffer, __alloc_buffer};
2022-06-08 16:17:38 +00:00
pub use plugin_macros::{export, import};
2022-06-02 15:49:02 +00:00
}