From bfc1fb8d68f39b899e544eee66e3a08abfd350b0 Mon Sep 17 00:00:00 2001 From: Divy Srivastava Date: Thu, 20 Oct 2022 16:03:57 +0530 Subject: [PATCH] perf(serde_v8): `serde_v8::StringOrBuffer` return JS ArrayBuffer instead of Uint8Array (#16360) Towards #16315 --- ext/websocket/01_websocket.js | 2 +- serde_v8/magic/string_or_buffer.rs | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/ext/websocket/01_websocket.js b/ext/websocket/01_websocket.js index 797d647231..4b0b4e941c 100644 --- a/ext/websocket/01_websocket.js +++ b/ext/websocket/01_websocket.js @@ -440,7 +440,7 @@ if (this.binaryType === "blob") { data = new Blob([value]); } else { - data = value.buffer; + data = value; } const event = new MessageEvent("message", { diff --git a/serde_v8/magic/string_or_buffer.rs b/serde_v8/magic/string_or_buffer.rs index aa7e26d2bb..582314d4b9 100644 --- a/serde_v8/magic/string_or_buffer.rs +++ b/serde_v8/magic/string_or_buffer.rs @@ -29,7 +29,24 @@ impl ToV8 for StringOrBuffer { scope: &mut v8::HandleScope<'a>, ) -> Result, crate::Error> { match self { - Self::Buffer(buf) => crate::to_v8(scope, buf), + Self::Buffer(buf) => { + let buf: Box<[u8]> = match buf { + ZeroCopyBuf::FromV8(buf) => { + let value: &[u8] = buf; + value.into() + } + ZeroCopyBuf::Temp(_) => unreachable!(), + ZeroCopyBuf::ToV8(ref mut x) => { + x.take().expect("ZeroCopyBuf was empty") + } + }; + let backing_store = + v8::ArrayBuffer::new_backing_store_from_boxed_slice(buf); + Ok( + v8::ArrayBuffer::with_backing_store(scope, &backing_store.into()) + .into(), + ) + } Self::String(s) => crate::to_v8(scope, s), } }