Skip to content

Commit

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

Signed-off-by: Stephan Renatus <srenatus@chef.io>
  • Loading branch information
srenatus committed Dec 20, 2019
1 parent 957bfd6 commit 782be5b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## **[Unreleased]**

- [#1092](https://github.com/wasmerio/wasmer/pull/1092) Add `get_utf8_string_with_nul` to `WasmPtr` to read nul-terminated strings from memory.

## 0.12.0 - 2019-12-18

Expand Down
11 changes: 11 additions & 0 deletions lib/runtime-core/src/memory/ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,17 @@ 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 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_with_nul<'a>(self, memory: &'a Memory) -> Option<&'a str> {
memory.view::<u8>()[(self.offset as usize)..]
.iter()
.map(|cell| cell.get())
.position(|byte| byte == 0)
.and_then(|length| self.get_utf8_string(memory, length as u32))
}
}

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

0 comments on commit 782be5b

Please sign in to comment.