diff --git a/lib/runtime-core/src/memory/ptr.rs b/lib/runtime-core/src/memory/ptr.rs index 5e31627c20f..770997ca3e4 100644 --- a/lib/runtime-core/src/memory/ptr.rs +++ b/lib/runtime-core/src/memory/ptr.rs @@ -10,7 +10,7 @@ use crate::{ memory::Memory, types::{ValueType, WasmExternType}, }; -use std::{cell::Cell, fmt, marker::PhantomData, mem}; +use std::{cell::Cell, convert::TryInto, fmt, marker::PhantomData, mem}; /// Array. pub struct Array; @@ -137,6 +137,17 @@ impl WasmPtr { let slice: &[u8] = unsafe { std::slice::from_raw_parts(ptr, str_len as usize) }; std::str::from_utf8(slice).ok() } + + /// Get a UTF-8 string representation of this `WasmPtr`, where the string is nul-terminated. + /// Note that this does not account for UTF-8 strings that _contain_ nul themselves, + /// [`get_utf8_string`] has to be used for those. + pub fn get_utf8_string_nul_terminated<'a>(self, memory: &'a Memory) -> Option<&'a str> { + memory.view::()[(self.offset as usize)..] + .iter() + .map(|cell| cell.get()) + .position(|byte| byte == 0) + .and_then(|length| self.get_utf8_string(memory, length.try_into().unwrap())) + } } unsafe impl WasmExternType for WasmPtr {