Skip to content

Commit

Permalink
Merge #1092
Browse files Browse the repository at this point in the history
1092: Add function to get nul-terminated strings from memory r=MarkMcCaskey a=srenatus

## Description

This is meant to fix #1086.

❓ I'm a bit new to this -- is this how you'd do it? Happy to take directions! 😃 

I've added a note regarding the special case in the comment.

Are there existing tests to expand?

## Review

- [x] Add a short description of the the change to the CHANGELOG.md file


Co-authored-by: Stephan Renatus <srenatus@chef.io>
  • Loading branch information
bors[bot] and srenatus authored Dec 20, 2019
2 parents 957bfd6 + 782be5b commit fa29a1b
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 fa29a1b

Please sign in to comment.