implement PLN-0033 vm string sharing hot path

This commit is contained in:
2026-04-20 08:45:34 +01:00
parent 8c5957a0a9
commit 09821cf9cc
10 changed files with 359 additions and 17 deletions
+1 -1
View File
@@ -6,4 +6,4 @@ license.workspace = true
repository.workspace = true
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde = { version = "1.0", features = ["derive", "rc"] }
@@ -75,7 +75,7 @@ impl From<BytecodeModule> for ProgramImage {
ConstantPoolEntry::Int64(v) => Value::Int64(*v),
ConstantPoolEntry::Float64(v) => Value::Float(*v),
ConstantPoolEntry::Boolean(v) => Value::Boolean(*v),
ConstantPoolEntry::String(v) => Value::String(v.clone()),
ConstantPoolEntry::String(v) => Value::String(v.clone().into()),
ConstantPoolEntry::Int32(v) => Value::Int32(*v),
})
.collect();
@@ -99,7 +99,7 @@ impl From<ProgramImage> for BytecodeModule {
Value::Int64(v) => ConstantPoolEntry::Int64(*v),
Value::Float(v) => ConstantPoolEntry::Float64(*v),
Value::Boolean(v) => ConstantPoolEntry::Boolean(*v),
Value::String(v) => ConstantPoolEntry::String(v.clone()),
Value::String(v) => ConstantPoolEntry::String(v.to_string()),
Value::Int32(v) => ConstantPoolEntry::Int32(*v),
Value::HeapRef(_) => ConstantPoolEntry::Null,
})
+41 -10
View File
@@ -1,5 +1,7 @@
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::fmt::Write;
use std::sync::Arc;
/// Opaque handle that references an object stored in the VM heap.
///
@@ -26,7 +28,7 @@ pub enum Value {
/// Boolean value (true/false).
Boolean(bool),
/// UTF-8 string. Strings are immutable and usually come from the Constant Pool.
String(String),
String(Arc<str>),
/// A handle to an object on the heap (opaque reference).
HeapRef(HeapRef),
/// Represents the absence of a value (equivalent to `null` or `undefined`).
@@ -92,17 +94,46 @@ impl Value {
}
}
pub fn append_to_string(&self, out: &mut String) {
match self {
Value::Int32(i) => {
let _ = write!(out, "{}", i);
}
Value::Int64(i) => {
let _ = write!(out, "{}", i);
}
Value::Float(f) => {
let _ = write!(out, "{}", f);
}
Value::Boolean(b) => {
let _ = write!(out, "{}", b);
}
Value::String(s) => out.push_str(s),
Value::HeapRef(r) => {
let _ = write!(out, "[HeapRef {}]", r.0);
}
Value::Null => out.push_str("null"),
}
}
pub fn string_len_hint(&self) -> usize {
match self {
Value::String(s) => s.len(),
Value::Null => 4,
Value::Boolean(true) => 4,
Value::Boolean(false) => 5,
Value::Int32(i) => i.to_string().len(),
Value::Int64(i) => i.to_string().len(),
Value::Float(f) => f.to_string().len(),
Value::HeapRef(r) => 11 + r.0.to_string().len(),
}
}
#[allow(clippy::inherent_to_string)]
pub fn to_string(&self) -> String {
match self {
Value::Int32(i) => i.to_string(),
Value::Int64(i) => i.to_string(),
Value::Float(f) => f.to_string(),
Value::Boolean(b) => b.to_string(),
Value::String(s) => s.clone(),
Value::HeapRef(r) => format!("[HeapRef {}]", r.0),
Value::Null => "null".to_string(),
}
let mut out = String::with_capacity(self.string_len_hint());
self.append_to_string(&mut out);
out
}
}
@@ -22,6 +22,6 @@ impl<'a> HostReturn<'a> {
self.stack.push(Value::HeapRef(HeapRef(g as u32)));
}
pub fn push_string(&mut self, s: String) {
self.stack.push(Value::String(s));
self.stack.push(Value::String(s.into()));
}
}
@@ -577,7 +577,7 @@ impl NativeInterface for VirtualMachineRuntime {
fn expect_string(args: &[Value], index: usize, field: &str) -> Result<String, VmFault> {
match args.get(index).ok_or_else(|| VmFault::Trap(TRAP_TYPE, format!("Missing {}", field)))? {
Value::String(value) => Ok(value.clone()),
Value::String(value) => Ok(value.to_string()),
_ => Err(VmFault::Trap(TRAP_TYPE, format!("Expected string {}", field))),
}
}
@@ -639,7 +639,10 @@ impl VirtualMachine {
}
OpCode::Add => self.binary_op(opcode, start_pc as u32, |a, b| match (&a, &b) {
(Value::String(_), _) | (_, Value::String(_)) => {
Ok(Value::String(format!("{}{}", a.to_string(), b.to_string())))
let mut out = String::with_capacity(a.string_len_hint() + b.string_len_hint());
a.append_to_string(&mut out);
b.append_to_string(&mut out);
Ok(Value::String(out.into()))
}
(Value::Int32(a), Value::Int32(b)) => Ok(Value::Int32(a.wrapping_add(*b))),
(Value::Int64(a), Value::Int64(b)) => Ok(Value::Int64(a.wrapping_add(*b))),
@@ -1213,6 +1216,7 @@ impl VirtualMachine {
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
fn new_test_vm(rom: Vec<u8>, constant_pool: Vec<Value>) -> VirtualMachine {
let rom_len = rom.len() as u32;
@@ -1642,6 +1646,19 @@ mod tests {
assert_eq!(vm.peek().unwrap(), &Value::String("hello".into()));
}
#[test]
fn test_shared_string_clone_reuses_materialized_payload() {
let mut vm = VirtualMachine::default();
let payload: Arc<str> = "shared-global".into();
vm.globals.push(Value::String(payload.clone()));
let cloned = vm.globals[0].clone();
match cloned {
Value::String(cloned_payload) => assert!(Arc::ptr_eq(&payload, &cloned_payload)),
other => panic!("expected string clone from globals, got {:?}", other),
}
}
#[test]
fn test_push_const_invalid_index_traps_oob() {
let mut rom = Vec::new();