Skip to content

Commit c43b96f

Browse files
committed
Add function to get NULL-terminated strings from memory
Fixes wasmerio#1086. Signed-off-by: Stephan Renatus <[email protected]>
1 parent 572399d commit c43b96f

File tree

1 file changed

+8
-1
lines changed
  • lib/runtime-core/src/memory

1 file changed

+8
-1
lines changed

lib/runtime-core/src/memory/ptr.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use crate::{
1010
memory::Memory,
1111
types::{ValueType, WasmExternType},
1212
};
13-
use std::{cell::Cell, fmt, marker::PhantomData, mem};
13+
use std::{cell::Cell, ffi::CStr, fmt, marker::PhantomData, mem};
1414

1515
/// Array.
1616
pub struct Array;
@@ -137,6 +137,13 @@ impl<T: Copy + ValueType> WasmPtr<T, Array> {
137137
let slice: &[u8] = unsafe { std::slice::from_raw_parts(ptr, str_len as usize) };
138138
std::str::from_utf8(slice).ok()
139139
}
140+
141+
/// Get a UTF-8 string representation of this `WasmPtr`, where the string is NULL-terminated.
142+
/// Note that this does not account for UTF-8 strings that _contain_ NULL themselves,
143+
/// [`get_utf8_string`] has to be used for those.
144+
pub fn get_utf8_string_null_terminated<'a>(self, memory: &'a Memory) -> Option<&'a str> {
145+
unsafe { CStr::from_ptr(memory.view::<u8>().as_ptr().add(self.offset as usize) as *const i8).to_str().ok() }
146+
}
140147
}
141148

142149
unsafe impl<T: Copy, Ty> WasmExternType for WasmPtr<T, Ty> {

0 commit comments

Comments
 (0)