Skip to content

Commit

Permalink
Add function to get NULL-terminated strings from memory
Browse files Browse the repository at this point in the history
Fixes wasmerio#1086.

Signed-off-by: Stephan Renatus <[email protected]>
  • Loading branch information
srenatus committed Dec 20, 2019
1 parent 572399d commit 4e6b605
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/runtime-core/src/memory/ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -137,6 +137,14 @@ impl<T: Copy + ValueType> WasmPtr<T, Array> {
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::<u8>().as_ptr().add(self.offset as usize) as *const i8) };
c_str.to_str().ok()
}
}

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

0 comments on commit 4e6b605

Please sign in to comment.