Skip to content

Commit

Permalink
Merge #56
Browse files Browse the repository at this point in the history
56: feat(memory) Add the `Memory.grow` method r=Hywan a=Hywan

This method can be used to grow the memory by a number of pages (65kb each).

Co-authored-by: Ivan Enderlin <[email protected]>
  • Loading branch information
bors[bot] and Hywan committed Jul 8, 2019
2 parents d9d7f73 + dbb7ea8 commit 8a86645
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,13 @@ print(repr(value_i32)) # I32(7)
A WebAssembly instance has its own memory, represented by the `Memory`
class. It is accessible by the `Instance.memory` getter.

The `Memory.grow` method allows to grow the memory by a number of
pages (of 65kb each).

```python
instance.memory.grow(1)
```

The `Memory` class offers methods to create views of the memory
internal buffer, e.g. `uint8_view`, `int8_view`, `uint16_view`
etc. All these methods accept one argument: `offset`, to subset the
Expand Down
10 changes: 9 additions & 1 deletion src/memory/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
//! Memory API of an WebAssembly instance.
use pyo3::prelude::*;
use pyo3::{exceptions::RuntimeError, prelude::*};
use std::rc::Rc;
use wasmer_runtime::Memory as WasmMemory;
use wasmer_runtime_core::units::Pages;

pub mod view;

Expand Down Expand Up @@ -78,4 +79,11 @@ impl Memory {
},
)
}

fn grow(&self, number_of_pages: u32) -> PyResult<u32> {
self.memory
.grow(Pages(number_of_pages))
.map(|previous_pages| previous_pages.0)
.map_err(|err| RuntimeError::py_err(format!("Failed to grow the memory: {}.", err)))
}
}
25 changes: 25 additions & 0 deletions tests/test_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,28 @@ def test_memory_views_share_the_same_buffer():
assert int16[0] == 0b00000100_00000001
assert int16[1] == 0b01000000_00010000
assert int32[0] == 0b01000000_00010000_00000100_00000001

def test_memory_grow():
instance = Instance(TEST_BYTES)
memory = instance.memory
int8 = memory.int8_view()

old_memory_length = len(int8)

assert old_memory_length == 1114112

memory.grow(1)

memory_length = len(int8)

assert memory_length == 1179648
assert memory_length - old_memory_length == 65536

def test_memory_grow_too_much():
with pytest.raises(RuntimeError) as context_manager:
Instance(TEST_BYTES).memory.grow(100000)

exception = context_manager.value
assert str(exception) == (
'Failed to grow the memory: Grow Error: Failed to add pages because would exceed maximum number of pages. Left: 17, Right: 100000, Pages added: 100017.'
)

0 comments on commit 8a86645

Please sign in to comment.