From 50a343a3ce6833bd074a3dccf813ab1ce2600c7c Mon Sep 17 00:00:00 2001 From: Haled Odat Date: Fri, 17 Mar 2023 00:16:44 +0000 Subject: [PATCH] Avoid unneeded bounds checks in bytecode address patching (#2680) As discussed in this comment https://github.com/boa-dev/boa/pull/2669#discussion_r1137618027, `rustc` doesn't seem to optimize out the bounds checks. --- boa_engine/src/bytecompiler/mod.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/boa_engine/src/bytecompiler/mod.rs b/boa_engine/src/bytecompiler/mod.rs index b10232878c..7b8ae96289 100644 --- a/boa_engine/src/bytecompiler/mod.rs +++ b/boa_engine/src/bytecompiler/mod.rs @@ -544,15 +544,16 @@ impl<'b, 'host> ByteCompiler<'b, 'host> { } fn patch_jump_with_target(&mut self, label: Label, target: u32) { + const U32_SIZE: usize = std::mem::size_of::(); + let Label { index } = label; let index = index as usize; - let bytes = target.to_ne_bytes(); - self.bytecode[index + 1] = bytes[0]; - self.bytecode[index + 2] = bytes[1]; - self.bytecode[index + 3] = bytes[2]; - self.bytecode[index + 4] = bytes[3]; + + // This is done to avoid unneeded bounds checks. + assert!(self.bytecode.len() > index + U32_SIZE && usize::MAX - U32_SIZE >= index); + self.bytecode[index + 1..=index + U32_SIZE].copy_from_slice(bytes.as_slice()); } fn patch_jump(&mut self, label: Label) {