From 4e6b60553066b1fb8831b1407e81fd7a90e033db Mon Sep 17 00:00:00 2001 From: Stephan Renatus Date: Fri, 20 Dec 2019 16:29:44 +0100 Subject: [PATCH] Add function to get NULL-terminated strings from memory Fixes #1086. Signed-off-by: Stephan Renatus --- lib/runtime-core/src/memory/ptr.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/runtime-core/src/memory/ptr.rs b/lib/runtime-core/src/memory/ptr.rs index 5e31627c20f..9377a423dee 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, ffi::CStr, fmt, marker::PhantomData, mem}; /// Array. pub struct Array; @@ -137,6 +137,14 @@ 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 NULL-terminated. + /// Note that this does not account for UTF-8 strings that _contain_ NULL themselves, + /// [`get_utf8_string`] has to be used for those. + pub fn get_utf8_string_null_terminated<'a>(self, memory: &'a Memory) -> Option<&'a str> { + let c_str = unsafe { CStr::from_ptr(memory.view::().as_ptr().add(self.offset as usize) as *const i8) }; + c_str.to_str().ok() + } } unsafe impl WasmExternType for WasmPtr {