Skip to content

Commit

Permalink
feat(c-api) Implement From<&[T]> for wasm_$name_vec_t for boxed vec.
Browse files Browse the repository at this point in the history
  • Loading branch information
Hywan committed Dec 17, 2020
1 parent 4abf6f8 commit 43026e6
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions lib/c-api/src/wasm_c_api/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ int main() {
macro_rules! wasm_declare_vec {
($name:ident) => {
paste::paste! {
#[doc = "Represents of a vector of `wasm_" $name "_t`.
#[doc = "Represents a vector of `wasm_" $name "_t`.
Read the documentation of [`wasm_" $name "_t`] to see more concrete examples.
Expand Down Expand Up @@ -107,6 +107,7 @@ int main() {
.into_boxed_slice();
let data = copied_data.as_mut_ptr();
::std::mem::forget(copied_data);

Self {
size,
data,
Expand Down Expand Up @@ -183,7 +184,9 @@ int main() {
macro_rules! wasm_declare_boxed_vec {
($name:ident) => {
paste::paste! {
#[doc = "Represents of a vector of [`wasm_" $name "_t`]."]
#[doc = "Represents a vector of `wasm_" $name "_t`.
Read the documentation of [`wasm_" $name "_t`] to see more concrete examples."]
#[derive(Debug)]
#[repr(C)]
pub struct [<wasm_ $name _vec_t>] {
Expand All @@ -206,6 +209,27 @@ macro_rules! wasm_declare_boxed_vec {
}
}

impl<'a, T: Into<[<wasm_ $name _t>]> + Clone> From<&'a [T]> for [<wasm_ $name _vec_t>] {
fn from(other: &'a [T]) -> Self {
let size = other.len();
let mut copied_data = other
.iter()
.cloned()
.map(Into::into)
.map(Box::new)
.map(Box::into_raw)
.collect::<Vec<*mut [<wasm_ $name _t>]>>()
.into_boxed_slice();
let data = copied_data.as_mut_ptr();
::std::mem::forget(copied_data);

Self {
size,
data,
}
}
}

// TODO: do this properly
impl [<wasm_ $name _vec_t>] {
pub unsafe fn into_slice(&self) -> Option<&[Box<[<wasm_ $name _t>]>]>{
Expand Down

0 comments on commit 43026e6

Please sign in to comment.