Skip to content

Commit

Permalink
feat(runtime/worker): Structured cloning worker message passing (deno…
Browse files Browse the repository at this point in the history
…land#9323)

This commit upgrade "Worker.postMessage()" implementation to use 
structured clone algorithm instead of non-spec compliant JSON serialization.
  • Loading branch information
inteon authored May 11, 2021
1 parent d4b8530 commit d4b670f
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions serde_v8/src/magic/buffer.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
use rusty_v8 as v8;

use std::cell::Cell;
use std::fmt;
use std::ops::Deref;
use std::ops::DerefMut;
use std::sync::Mutex;

use super::zero_copy_buf::ZeroCopyBuf;

// An asymmetric wrapper around ZeroCopyBuf,
// allowing us to use a single type for familiarity
pub enum MagicBuffer {
FromV8(ZeroCopyBuf),
ToV8(Cell<Option<Box<[u8]>>>),
ToV8(Mutex<Option<Box<[u8]>>>),
}

impl MagicBuffer {
Expand All @@ -21,6 +21,10 @@ impl MagicBuffer {
) -> Self {
Self::FromV8(ZeroCopyBuf::new(scope, view))
}

pub fn empty() -> Self {
MagicBuffer::ToV8(Mutex::new(Some(vec![0_u8; 0].into_boxed_slice())))
}
}

impl Clone for MagicBuffer {
Expand Down Expand Up @@ -65,7 +69,7 @@ impl DerefMut for MagicBuffer {

impl From<Box<[u8]>> for MagicBuffer {
fn from(buf: Box<[u8]>) -> Self {
MagicBuffer::ToV8(Cell::new(Some(buf)))
MagicBuffer::ToV8(Mutex::new(Some(buf)))
}
}

Expand All @@ -88,8 +92,11 @@ impl serde::Serialize for MagicBuffer {

let mut s = serializer.serialize_struct(BUF_NAME, 1)?;
let boxed: Box<[u8]> = match self {
Self::FromV8(_) => unreachable!(),
Self::ToV8(x) => x.take().expect("MagicBuffer was empty"),
Self::FromV8(buf) => {
let value: &[u8] = &buf;
value.into()
}
Self::ToV8(x) => x.lock().unwrap().take().expect("MagicBuffer was empty"),
};
let hack: [usize; 2] = unsafe { std::mem::transmute(boxed) };
let f1: u64 = hack[0] as u64;
Expand Down

0 comments on commit d4b670f

Please sign in to comment.