Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add function to get nul-terminated strings from memory #1092

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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