#[cfg_attr(not(target_arch = "wasm32"), allow(unused))]
#[cfg(any(feature = "__plugin_rt", feature = "__plugin_mode"))]
use swc_common::plugin::serialized::PluginSerializedBytes;
#[cfg_attr(
feature = "__rkyv",
derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
#[cfg_attr(feature = "__rkyv", archive(check_bytes))]
#[cfg_attr(feature = "__rkyv", archive_attr(repr(C)))]
pub struct AllocatedBytesPtr(pub u32, pub u32);
#[cfg(target_arch = "wasm32")]
extern "C" {
fn __free(ptr: *mut u8, size: i32) -> i32;
}
#[cfg(target_arch = "wasm32")]
impl Drop for AllocatedBytesPtr {
fn drop(&mut self) {
unsafe {
__free(self.0 as _, self.1 as _);
}
}
}
#[cfg(not(feature = "__rkyv"))]
fn read_returned_result_from_host_inner<F>(f: F) -> Option<AllocatedBytesPtr> {
unimplemented!("Plugin proxy does not work without serialization support")
}
#[cfg(all(feature = "__rkyv", feature = "__plugin_mode", target_arch = "wasm32"))]
#[tracing::instrument(level = "info", skip_all)]
fn read_returned_result_from_host_inner<F>(f: F) -> Option<AllocatedBytesPtr>
where
F: FnOnce(u32) -> u32,
{
let allocated_bytes_ptr =
swc_common::plugin::serialized::VersionedSerializable::new(AllocatedBytesPtr(0, 0));
let serialized_allocated_bytes_ptr = PluginSerializedBytes::try_serialize(&allocated_bytes_ptr)
.expect("Should able to serialize AllocatedBytesPtr");
let (serialized_allocated_bytes_raw_ptr, serialized_allocated_bytes_raw_ptr_size) =
serialized_allocated_bytes_ptr.as_ptr();
std::mem::forget(allocated_bytes_ptr); let ret = f(serialized_allocated_bytes_raw_ptr as _);
if ret == 0 {
return None;
}
Some(
PluginSerializedBytes::from_raw_ptr(
serialized_allocated_bytes_raw_ptr,
serialized_allocated_bytes_raw_ptr_size
.try_into()
.expect("Should able to convert ptr length"),
)
.deserialize()
.expect("Should able to deserialize AllocatedBytesPtr")
.into_inner(),
)
}
#[cfg(not(feature = "__rkyv"))]
pub fn read_returned_result_from_host<F, R>(f: F) -> Option<R> {
unimplemented!("Plugin proxy does not work without serialization support")
}
#[cfg(all(feature = "__rkyv", feature = "__plugin_mode", target_arch = "wasm32"))]
#[cfg_attr(not(target_arch = "wasm32"), allow(unused))]
#[tracing::instrument(level = "info", skip_all)]
pub fn read_returned_result_from_host<F, R>(f: F) -> Option<R>
where
F: FnOnce(u32) -> u32,
R: rkyv::Archive,
R::Archived: rkyv::Deserialize<R, rkyv::de::deserializers::SharedDeserializeMap>,
{
let allocated_returned_value_ptr = read_returned_result_from_host_inner(f);
allocated_returned_value_ptr.map(|allocated_returned_value_ptr| {
PluginSerializedBytes::from_raw_ptr(
allocated_returned_value_ptr.0 as _,
allocated_returned_value_ptr
.1
.try_into()
.expect("Should able to convert ptr length"),
)
.deserialize()
.expect("Returned value should be serializable")
.into_inner()
})
}