Migrated internal samples to new Context API

This commit is contained in:
ptitSeb
2022-06-30 15:37:39 +02:00
committed by Manos Pitsidianakis
parent 267a09ce8e
commit d12759f150
12 changed files with 156 additions and 96 deletions

View File

@@ -41,6 +41,7 @@
//! //!
//! ```rust //! ```rust
//! use wasmer::{Store, Module, Instance, Value, imports}; //! use wasmer::{Store, Module, Instance, Value, imports};
//! use wasmer::Context as WasmerContext;
//! //!
//! fn main() -> anyhow::Result<()> { //! fn main() -> anyhow::Result<()> {
//! let module_wat = r#" //! let module_wat = r#"
@@ -53,13 +54,14 @@
//! "#; //! "#;
//! //!
//! let store = Store::default(); //! let store = Store::default();
//! let mut ctx = WasmerContext::new(&store, ());
//! let module = Module::new(&store, &module_wat)?; //! let module = Module::new(&store, &module_wat)?;
//! // The module doesn't import anything, so we create an empty import object. //! // The module doesn't import anything, so we create an empty import object.
//! let import_object = imports! {}; //! let import_object = imports! {};
//! let instance = Instance::new(&module, &import_object)?; //! let instance = Instance::new(&mut ctx, &module, &import_object)?;
//! //!
//! let add_one = instance.exports.get_function("add_one")?; //! let add_one = instance.exports.get_function("add_one")?;
//! let result = add_one.call(&[Value::I32(42)])?; //! let result = add_one.call(&mut ctx, &[Value::I32(42)])?;
//! assert_eq!(result[0], Value::I32(43)); //! assert_eq!(result[0], Value::I32(43));
//! //!
//! Ok(()) //! Ok(())
@@ -150,11 +152,12 @@
//! //!
//! ``` //! ```
//! # use wasmer::{imports, Function, Memory, MemoryType, Store, Imports}; //! # use wasmer::{imports, Function, Memory, MemoryType, Store, Imports};
//! # fn imports_example(store: &Store) -> Imports { //! # use wasmer::ContextMut;
//! let memory = Memory::new(&store, MemoryType::new(1, None, false)).unwrap(); //! # fn imports_example(mut ctx: ContextMut<()>, store: &Store) -> Imports {
//! let memory = Memory::new(&mut ctx, MemoryType::new(1, None, false)).unwrap();
//! imports! { //! imports! {
//! "env" => { //! "env" => {
//! "my_function" => Function::new_native(store, || println!("Hello")), //! "my_function" => Function::new_native(&mut ctx, |_ctx: ContextMut<()>| println!("Hello")),
//! "memory" => memory, //! "memory" => memory,
//! } //! }
//! } //! }
@@ -165,12 +168,12 @@
//! from any instance via `instance.exports`: //! from any instance via `instance.exports`:
//! //!
//! ``` //! ```
//! # use wasmer::{imports, Instance, Function, Memory, TypedFunction}; //! # use wasmer::{imports, Instance, Function, Memory, TypedFunction, ContextMut};
//! # fn exports_example(instance: &Instance) -> anyhow::Result<()> { //! # fn exports_example(mut ctx: ContextMut<()>, instance: &Instance) -> anyhow::Result<()> {
//! let memory = instance.exports.get_memory("memory")?; //! let memory = instance.exports.get_memory("memory")?;
//! let memory: &Memory = instance.exports.get("some_other_memory")?; //! let memory: &Memory = instance.exports.get("some_other_memory")?;
//! let add: TypedFunction<(i32, i32), i32> = instance.exports.get_typed_function("add")?; //! let add: TypedFunction<(i32, i32), i32> = instance.exports.get_typed_function(&mut ctx, "add")?;
//! let result = add.call(5, 37)?; //! let result = add.call(&mut ctx, 5, 37)?;
//! assert_eq!(result, 42); //! assert_eq!(result, 42);
//! # Ok(()) //! # Ok(())
//! # } //! # }

View File

@@ -18,14 +18,16 @@ use thiserror::Error;
/// ///
/// ```should_panic /// ```should_panic
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value, ExportError}; /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value, ExportError};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # let wasm_bytes = wat2wasm(r#" /// # let wasm_bytes = wat2wasm(r#"
/// # (module /// # (module
/// # (global $one (export "glob") f32 (f32.const 1))) /// # (global $one (export "glob") f32 (f32.const 1)))
/// # "#.as_bytes()).unwrap(); /// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap(); /// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {}; /// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap(); /// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap();
/// # /// #
/// // This results with an error: `ExportError::IncompatibleType`. /// // This results with an error: `ExportError::IncompatibleType`.
/// let export = instance.exports.get_function("glob").unwrap(); /// let export = instance.exports.get_function("glob").unwrap();
@@ -35,11 +37,13 @@ use thiserror::Error;
/// ///
/// ```should_panic /// ```should_panic
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value, ExportError}; /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value, ExportError};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # let wasm_bytes = wat2wasm("(module)".as_bytes()).unwrap(); /// # let wasm_bytes = wat2wasm("(module)".as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap(); /// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {}; /// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap(); /// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap();
/// # /// #
/// // This results with an error: `ExportError::Missing`. /// // This results with an error: `ExportError::Missing`.
/// let export = instance.exports.get_function("unknown").unwrap(); /// let export = instance.exports.get_function("unknown").unwrap();

View File

@@ -51,11 +51,13 @@ impl Function {
/// ///
/// ``` /// ```
/// # use wasmer::{Function, FunctionType, Type, Store, Value}; /// # use wasmer::{Function, FunctionType, Type, Store, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]); /// let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]);
/// ///
/// let f = Function::new(&store, &signature, |args| { /// let f = Function::new(&mut ctx, &signature, |_ctx, args| {
/// let sum = args[0].unwrap_i32() + args[1].unwrap_i32(); /// let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
/// Ok(vec![Value::I32(sum)]) /// Ok(vec![Value::I32(sum)])
/// }); /// });
@@ -65,11 +67,13 @@ impl Function {
/// ///
/// ``` /// ```
/// # use wasmer::{Function, FunctionType, Type, Store, Value}; /// # use wasmer::{Function, FunctionType, Type, Store, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]); /// const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]);
/// ///
/// let f = Function::new(&store, I32_I32_TO_I32, |args| { /// let f = Function::new(&mut ctx, I32_I32_TO_I32, |_ctx, args| {
/// let sum = args[0].unwrap_i32() + args[1].unwrap_i32(); /// let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
/// Ok(vec![Value::I32(sum)]) /// Ok(vec![Value::I32(sum)])
/// }); /// });
@@ -152,14 +156,16 @@ impl Function {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # use wasmer::{Store, Function}; /// # use wasmer::{ContextMut, Store, Function};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// fn sum(a: i32, b: i32) -> i32 { /// fn sum(_ctx: ContextMut<()>, a: i32, b: i32) -> i32 {
/// a + b /// a + b
/// } /// }
/// ///
/// let f = Function::new_native(&store, sum); /// let f = Function::new_native(&mut ctx, sum);
/// ``` /// ```
pub fn new_native<T, F, Args, Rets>(ctx: &mut impl AsContextMut<Data = T>, func: F) -> Self pub fn new_native<T, F, Args, Rets>(ctx: &mut impl AsContextMut<Data = T>, func: F) -> Self
where where
@@ -203,17 +209,19 @@ impl Function {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # use wasmer::{Function, Store, Type}; /// # use wasmer::{ContextMut, Function, Store, Type};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// fn sum(a: i32, b: i32) -> i32 { /// fn sum(_ctx: ContextMut<()>, a: i32, b: i32) -> i32 {
/// a + b /// a + b
/// } /// }
/// ///
/// let f = Function::new_native(&store, sum); /// let f = Function::new_native(&mut ctx, sum);
/// ///
/// assert_eq!(f.ty().params(), vec![Type::I32, Type::I32]); /// assert_eq!(f.ty(&mut ctx).params(), vec![Type::I32, Type::I32]);
/// assert_eq!(f.ty().results(), vec![Type::I32]); /// assert_eq!(f.ty(&mut ctx).results(), vec![Type::I32]);
/// ``` /// ```
pub fn ty(&self, ctx: &impl AsContextRef) -> FunctionType { pub fn ty(&self, ctx: &impl AsContextRef) -> FunctionType {
self.handle self.handle
@@ -302,16 +310,18 @@ impl Function {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # use wasmer::{Function, Store, Type}; /// # use wasmer::{ContextMut, Function, Store, Type};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// fn sum(a: i32, b: i32) -> i32 { /// fn sum(_ctx: ContextMut<()>, a: i32, b: i32) -> i32 {
/// a + b /// a + b
/// } /// }
/// ///
/// let f = Function::new_native(&store, sum); /// let f = Function::new_native(&mut ctx, sum);
/// ///
/// assert_eq!(f.param_arity(), 2); /// assert_eq!(f.param_arity(&mut ctx), 2);
/// ``` /// ```
pub fn param_arity(&self, ctx: &impl AsContextRef) -> usize { pub fn param_arity(&self, ctx: &impl AsContextRef) -> usize {
self.ty(ctx).params().len() self.ty(ctx).params().len()
@@ -322,16 +332,18 @@ impl Function {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # use wasmer::{Function, Store, Type}; /// # use wasmer::{ContextMut, Function, Store, Type};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// fn sum(a: i32, b: i32) -> i32 { /// fn sum(_ctx: ContextMut<()>, a: i32, b: i32) -> i32 {
/// a + b /// a + b
/// } /// }
/// ///
/// let f = Function::new_native(&store, sum); /// let f = Function::new_native(&mut ctx, sum);
/// ///
/// assert_eq!(f.result_arity(), 1); /// assert_eq!(f.result_arity(&mut ctx), 1);
/// ``` /// ```
pub fn result_arity(&self, ctx: &impl AsContextRef) -> usize { pub fn result_arity(&self, ctx: &impl AsContextRef) -> usize {
self.ty(ctx).results().len() self.ty(ctx).results().len()
@@ -349,7 +361,9 @@ impl Function {
/// ///
/// ``` /// ```
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value}; /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # let wasm_bytes = wat2wasm(r#" /// # let wasm_bytes = wat2wasm(r#"
/// # (module /// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32) /// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
@@ -360,11 +374,11 @@ impl Function {
/// # "#.as_bytes()).unwrap(); /// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap(); /// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {}; /// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap(); /// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap();
/// # /// #
/// let sum = instance.exports.get_function("sum").unwrap(); /// let sum = instance.exports.get_function("sum").unwrap();
/// ///
/// assert_eq!(sum.call(&[Value::I32(1), Value::I32(2)]).unwrap().to_vec(), vec![Value::I32(3)]); /// assert_eq!(sum.call(&mut ctx, &[Value::I32(1), Value::I32(2)]).unwrap().to_vec(), vec![Value::I32(3)]);
/// ``` /// ```
pub fn call( pub fn call(
&self, &self,
@@ -418,8 +432,10 @@ impl Function {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value}; /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, TypedFunction, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # let wasm_bytes = wat2wasm(r#" /// # let wasm_bytes = wat2wasm(r#"
/// # (module /// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32) /// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
@@ -430,12 +446,12 @@ impl Function {
/// # "#.as_bytes()).unwrap(); /// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap(); /// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {}; /// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap(); /// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap();
/// # /// #
/// let sum = instance.exports.get_function("sum").unwrap(); /// let sum = instance.exports.get_function("sum").unwrap();
/// let sum_native = sum.native::<(i32, i32), i32>().unwrap(); /// let sum_native: TypedFunction<(i32, i32), i32> = sum.native(&mut ctx).unwrap();
/// ///
/// assert_eq!(sum_native.call(1, 2).unwrap(), 3); /// assert_eq!(sum_native.call(&mut ctx, 1, 2).unwrap(), 3);
/// ``` /// ```
/// ///
/// # Errors /// # Errors
@@ -444,8 +460,10 @@ impl Function {
/// an error will be raised: /// an error will be raised:
/// ///
/// ```should_panic /// ```should_panic
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value}; /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, TypedFunction, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # let wasm_bytes = wat2wasm(r#" /// # let wasm_bytes = wat2wasm(r#"
/// # (module /// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32) /// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
@@ -456,20 +474,22 @@ impl Function {
/// # "#.as_bytes()).unwrap(); /// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap(); /// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {}; /// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap(); /// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap();
/// # /// #
/// let sum = instance.exports.get_function("sum").unwrap(); /// let sum = instance.exports.get_function("sum").unwrap();
/// ///
/// // This results in an error: `RuntimeError` /// // This results in an error: `RuntimeError`
/// let sum_native = sum.native::<(i64, i64), i32>().unwrap(); /// let sum_native : TypedFunction<(i64, i64), i32> = sum.native(&mut ctx).unwrap();
/// ``` /// ```
/// ///
/// If the `Rets` generic parameter does not match the exported function /// If the `Rets` generic parameter does not match the exported function
/// an error will be raised: /// an error will be raised:
/// ///
/// ```should_panic /// ```should_panic
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value}; /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, TypedFunction, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # let wasm_bytes = wat2wasm(r#" /// # let wasm_bytes = wat2wasm(r#"
/// # (module /// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32) /// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
@@ -480,12 +500,12 @@ impl Function {
/// # "#.as_bytes()).unwrap(); /// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap(); /// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {}; /// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap(); /// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap();
/// # /// #
/// let sum = instance.exports.get_function("sum").unwrap(); /// let sum = instance.exports.get_function("sum").unwrap();
/// ///
/// // This results in an error: `RuntimeError` /// // This results in an error: `RuntimeError`
/// let sum_native = sum.native::<(i32, i32), i64>().unwrap(); /// let sum_native: TypedFunction<(i32, i32), i64> = sum.native(&mut ctx).unwrap();
/// ``` /// ```
pub fn native<Args, Rets>( pub fn native<Args, Rets>(
&self, &self,

View File

@@ -25,12 +25,14 @@ impl Global {
/// ///
/// ``` /// ```
/// # use wasmer::{Global, Mutability, Store, Value}; /// # use wasmer::{Global, Mutability, Store, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// let g = Global::new(&store, Value::I32(1)); /// let g = Global::new(&mut ctx, Value::I32(1));
/// ///
/// assert_eq!(g.get(), Value::I32(1)); /// assert_eq!(g.get(&mut ctx), Value::I32(1));
/// assert_eq!(g.ty().mutability, Mutability::Const); /// assert_eq!(g.ty(&mut ctx).mutability, Mutability::Const);
/// ``` /// ```
pub fn new(ctx: &mut impl AsContextMut, val: Value) -> Self { pub fn new(ctx: &mut impl AsContextMut, val: Value) -> Self {
Self::from_value(ctx, val, Mutability::Const).unwrap() Self::from_value(ctx, val, Mutability::Const).unwrap()
@@ -42,12 +44,14 @@ impl Global {
/// ///
/// ``` /// ```
/// # use wasmer::{Global, Mutability, Store, Value}; /// # use wasmer::{Global, Mutability, Store, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// let g = Global::new_mut(&store, Value::I32(1)); /// let g = Global::new_mut(&mut ctx, Value::I32(1));
/// ///
/// assert_eq!(g.get(), Value::I32(1)); /// assert_eq!(g.get(&mut ctx), Value::I32(1));
/// assert_eq!(g.ty().mutability, Mutability::Var); /// assert_eq!(g.ty(&mut ctx).mutability, Mutability::Var);
/// ``` /// ```
pub fn new_mut(ctx: &mut impl AsContextMut, val: Value) -> Self { pub fn new_mut(ctx: &mut impl AsContextMut, val: Value) -> Self {
Self::from_value(ctx, val, Mutability::Var).unwrap() Self::from_value(ctx, val, Mutability::Var).unwrap()
@@ -83,13 +87,15 @@ impl Global {
/// ///
/// ``` /// ```
/// # use wasmer::{Global, Mutability, Store, Type, Value, GlobalType}; /// # use wasmer::{Global, Mutability, Store, Type, Value, GlobalType};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// let c = Global::new(&store, Value::I32(1)); /// let c = Global::new(&mut ctx, Value::I32(1));
/// let v = Global::new_mut(&store, Value::I64(1)); /// let v = Global::new_mut(&mut ctx, Value::I64(1));
/// ///
/// assert_eq!(c.ty(), &GlobalType::new(Type::I32, Mutability::Const)); /// assert_eq!(c.ty(&mut ctx), GlobalType::new(Type::I32, Mutability::Const));
/// assert_eq!(v.ty(), &GlobalType::new(Type::I64, Mutability::Var)); /// assert_eq!(v.ty(&mut ctx), GlobalType::new(Type::I64, Mutability::Var));
/// ``` /// ```
pub fn ty(&self, ctx: &impl AsContextRef) -> GlobalType { pub fn ty(&self, ctx: &impl AsContextRef) -> GlobalType {
*self.handle.get(ctx.as_context_ref().objects()).ty() *self.handle.get(ctx.as_context_ref().objects()).ty()
@@ -101,11 +107,13 @@ impl Global {
/// ///
/// ``` /// ```
/// # use wasmer::{Global, Store, Value}; /// # use wasmer::{Global, Store, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// let g = Global::new(&store, Value::I32(1)); /// let g = Global::new(&mut ctx, Value::I32(1));
/// ///
/// assert_eq!(g.get(), Value::I32(1)); /// assert_eq!(g.get(&mut ctx), Value::I32(1));
/// ``` /// ```
pub fn get(&self, ctx: &mut impl AsContextMut) -> Value { pub fn get(&self, ctx: &mut impl AsContextMut) -> Value {
unsafe { unsafe {
@@ -126,15 +134,17 @@ impl Global {
/// ///
/// ``` /// ```
/// # use wasmer::{Global, Store, Value}; /// # use wasmer::{Global, Store, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// let g = Global::new_mut(&store, Value::I32(1)); /// let g = Global::new_mut(&mut ctx, Value::I32(1));
/// ///
/// assert_eq!(g.get(), Value::I32(1)); /// assert_eq!(g.get(&mut ctx), Value::I32(1));
/// ///
/// g.set(Value::I32(2)); /// g.set(&mut ctx, Value::I32(2));
/// ///
/// assert_eq!(g.get(), Value::I32(2)); /// assert_eq!(g.get(&mut ctx), Value::I32(2));
/// ``` /// ```
/// ///
/// # Errors /// # Errors
@@ -143,23 +153,27 @@ impl Global {
/// ///
/// ```should_panic /// ```should_panic
/// # use wasmer::{Global, Store, Value}; /// # use wasmer::{Global, Store, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// let g = Global::new(&store, Value::I32(1)); /// let g = Global::new(&mut ctx, Value::I32(1));
/// ///
/// g.set(Value::I32(2)).unwrap(); /// g.set(&mut ctx, Value::I32(2)).unwrap();
/// ``` /// ```
/// ///
/// Trying to set a value of a incompatible type will raise an error: /// Trying to set a value of a incompatible type will raise an error:
/// ///
/// ```should_panic /// ```should_panic
/// # use wasmer::{Global, Store, Value}; /// # use wasmer::{Global, Store, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// let g = Global::new(&store, Value::I32(1)); /// let g = Global::new(&mut ctx, Value::I32(1));
/// ///
/// // This results in an error: `RuntimeError`. /// // This results in an error: `RuntimeError`.
/// g.set(Value::I64(2)).unwrap(); /// g.set(&mut ctx, Value::I64(2)).unwrap();
/// ``` /// ```
pub fn set(&self, ctx: &mut impl AsContextMut, val: Value) -> Result<(), RuntimeError> { pub fn set(&self, ctx: &mut impl AsContextMut, val: Value) -> Result<(), RuntimeError> {
if !val.is_from_context(ctx) { if !val.is_from_context(ctx) {

View File

@@ -42,9 +42,11 @@ impl Memory {
/// ///
/// ``` /// ```
/// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value}; /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// let m = Memory::new(&store, MemoryType::new(1, None, false)).unwrap(); /// let m = Memory::new(&mut ctx, MemoryType::new(1, None, false)).unwrap();
/// ``` /// ```
pub fn new(ctx: &mut impl AsContextMut, ty: MemoryType) -> Result<Self, MemoryError> { pub fn new(ctx: &mut impl AsContextMut, ty: MemoryType) -> Result<Self, MemoryError> {
let mut ctx = ctx.as_context_mut(); let mut ctx = ctx.as_context_mut();
@@ -63,12 +65,14 @@ impl Memory {
/// ///
/// ``` /// ```
/// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value}; /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// let mt = MemoryType::new(1, None, false); /// let mt = MemoryType::new(1, None, false);
/// let m = Memory::new(&store, mt).unwrap(); /// let m = Memory::new(&mut ctx, mt).unwrap();
/// ///
/// assert_eq!(m.ty(), mt); /// assert_eq!(m.ty(&mut ctx), mt);
/// ``` /// ```
pub fn ty(&self, ctx: &impl AsContextRef) -> MemoryType { pub fn ty(&self, ctx: &impl AsContextRef) -> MemoryType {
self.handle.get(ctx.as_context_ref().objects()).ty() self.handle.get(ctx.as_context_ref().objects()).ty()
@@ -94,11 +98,13 @@ impl Memory {
/// ///
/// ``` /// ```
/// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value}; /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// let m = Memory::new(&store, MemoryType::new(1, None, false)).unwrap(); /// let m = Memory::new(&mut ctx, MemoryType::new(1, None, false)).unwrap();
/// ///
/// assert_eq!(m.size(), Pages(1)); /// assert_eq!(m.size(&mut ctx), Pages(1));
/// ``` /// ```
pub fn size(&self, ctx: &impl AsContextRef) -> Pages { pub fn size(&self, ctx: &impl AsContextRef) -> Pages {
self.handle.get(ctx.as_context_ref().objects()).size() self.handle.get(ctx.as_context_ref().objects()).size()
@@ -111,13 +117,15 @@ impl Memory {
/// ///
/// ``` /// ```
/// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value, WASM_MAX_PAGES}; /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value, WASM_MAX_PAGES};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// let m = Memory::new(&store, MemoryType::new(1, Some(3), false)).unwrap(); /// let m = Memory::new(&mut ctx, MemoryType::new(1, Some(3), false)).unwrap();
/// let p = m.grow(2).unwrap(); /// let p = m.grow(&mut ctx, 2).unwrap();
/// ///
/// assert_eq!(p, Pages(1)); /// assert_eq!(p, Pages(1));
/// assert_eq!(m.size(), Pages(3)); /// assert_eq!(m.size(&mut ctx), Pages(3));
/// ``` /// ```
/// ///
/// # Errors /// # Errors
@@ -127,12 +135,14 @@ impl Memory {
/// ///
/// ```should_panic /// ```should_panic
/// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value, WASM_MAX_PAGES}; /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value, WASM_MAX_PAGES};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # /// #
/// let m = Memory::new(&store, MemoryType::new(1, Some(1), false)).unwrap(); /// let m = Memory::new(&mut ctx, MemoryType::new(1, Some(1), false)).unwrap();
/// ///
/// // This results in an error: `MemoryError::CouldNotGrow`. /// // This results in an error: `MemoryError::CouldNotGrow`.
/// let s = m.grow(1).unwrap(); /// let s = m.grow(&mut ctx, 1).unwrap();
/// ``` /// ```
pub fn grow<IntoPages>( pub fn grow<IntoPages>(
&self, &self,

View File

@@ -16,19 +16,19 @@ use wasmer_types::ImportError;
/// ///
/// # Usage: /// # Usage:
/// ```no_run /// ```no_run
/// use wasmer::{Exports, Module, Store, Instance, imports, Imports, Function}; /// use wasmer::{ContextMut, Exports, Module, Instance, imports, Imports, Function};
/// # fn foo_test(module: Module, store: Store) { /// # fn foo_test(mut ctx: ContextMut<()>, module: Module) {
/// ///
/// let host_fn = Function::new_native(&store, foo); /// let host_fn = Function::new_native(&mut ctx, foo);
/// let import_object: Imports = imports! { /// let import_object: Imports = imports! {
/// "env" => { /// "env" => {
/// "foo" => host_fn, /// "foo" => host_fn,
/// }, /// },
/// }; /// };
/// ///
/// let instance = Instance::new(&module, &import_object).expect("Could not instantiate module."); /// let instance = Instance::new(&mut ctx, &module, &import_object).expect("Could not instantiate module.");
/// ///
/// fn foo(n: i32) -> i32 { /// fn foo(_ctx: ContextMut<()>, n: i32) -> i32 {
/// n /// n
/// } /// }
/// ///
@@ -97,13 +97,15 @@ impl Imports {
/// ///
/// # Usage /// # Usage
/// ```no_run /// ```no_run
/// # use wasmer::Context as WasmerContext;
/// # let store = Default::default(); /// # let store = Default::default();
/// use wasmer::{Imports, Function}; /// # let mut ctx = WasmerContext::new(&store, ());
/// fn foo(n: i32) -> i32 { /// use wasmer::{ContextMut, Imports, Function};
/// fn foo(_ctx: ContextMut<()>, n: i32) -> i32 {
/// n /// n
/// } /// }
/// let mut import_object = Imports::new(); /// let mut import_object = Imports::new();
/// import_object.define("env", "foo", Function::new_native(&store, foo)); /// import_object.define("env", "foo", Function::new_native(&mut ctx, foo));
/// ``` /// ```
pub fn define(&mut self, ns: &str, name: &str, val: impl Into<Extern>) { pub fn define(&mut self, ns: &str, name: &str, val: impl Into<Extern>) {
self.map self.map
@@ -208,17 +210,19 @@ impl fmt::Debug for Imports {
/// # Usage /// # Usage
/// ///
/// ``` /// ```
/// # use wasmer::{Function, Store}; /// # use wasmer::{ContextMut, Function, Store};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default(); /// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// use wasmer::imports; /// use wasmer::imports;
/// ///
/// let import_object = imports! { /// let import_object = imports! {
/// "env" => { /// "env" => {
/// "foo" => Function::new_native(&store, foo) /// "foo" => Function::new_native(&mut ctx, foo)
/// }, /// },
/// }; /// };
/// ///
/// fn foo(n: i32) -> i32 { /// fn foo(_ctx: ContextMut<()>, n: i32) -> i32 {
/// n /// n
/// } /// }
/// ``` /// ```

View File

@@ -87,15 +87,17 @@ impl Instance {
/// ///
/// ``` /// ```
/// # use wasmer::{imports, Store, Module, Global, Value, Instance}; /// # use wasmer::{imports, Store, Module, Global, Value, Instance};
/// # use wasmer::Context as WasmerContext;
/// # fn main() -> anyhow::Result<()> { /// # fn main() -> anyhow::Result<()> {
/// let store = Store::default(); /// let store = Store::default();
/// let mut ctx = WasmerContext::new(&store, ());
/// let module = Module::new(&store, "(module)")?; /// let module = Module::new(&store, "(module)")?;
/// let imports = imports!{ /// let imports = imports!{
/// "host" => { /// "host" => {
/// "var" => Global::new(&store, Value::I32(2)) /// "var" => Global::new(&mut ctx, Value::I32(2))
/// } /// }
/// }; /// };
/// let instance = Instance::new(&module, &imports)?; /// let instance = Instance::new(&mut ctx, &module, &imports)?;
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```

View File

@@ -23,8 +23,9 @@ pub type WasmPtr64<T> = WasmPtr<T, Memory64>;
/// ``` /// ```
/// # use wasmer::Memory; /// # use wasmer::Memory;
/// # use wasmer::WasmPtr; /// # use wasmer::WasmPtr;
/// pub fn host_import(memory: Memory, ptr: WasmPtr<u32>) { /// # use wasmer::ContextMut;
/// let derefed_ptr = ptr.deref(&memory); /// pub fn host_import(mut ctx: ContextMut<()>, memory: Memory, ptr: WasmPtr<u32>) {
/// let derefed_ptr = ptr.deref(&mut ctx, &memory);
/// let inner_val: u32 = derefed_ptr.read().expect("pointer in bounds"); /// let inner_val: u32 = derefed_ptr.read().expect("pointer in bounds");
/// println!("Got {} from Wasm memory address 0x{:X}", inner_val, ptr.offset()); /// println!("Got {} from Wasm memory address 0x{:X}", inner_val, ptr.offset());
/// // update the value being pointed to /// // update the value being pointed to
@@ -38,6 +39,7 @@ pub type WasmPtr64<T> = WasmPtr<T, Memory64>;
/// # use wasmer::Memory; /// # use wasmer::Memory;
/// # use wasmer::WasmPtr; /// # use wasmer::WasmPtr;
/// # use wasmer::ValueType; /// # use wasmer::ValueType;
/// # use wasmer::ContextMut;
/// ///
/// // This is safe as the 12 bytes represented by this struct /// // This is safe as the 12 bytes represented by this struct
/// // are valid for all bit combinations. /// // are valid for all bit combinations.
@@ -49,8 +51,8 @@ pub type WasmPtr64<T> = WasmPtr<T, Memory64>;
/// z: f32 /// z: f32
/// } /// }
/// ///
/// fn update_vector_3(memory: Memory, ptr: WasmPtr<V3>) { /// fn update_vector_3(mut ctx: ContextMut<()>, memory: Memory, ptr: WasmPtr<V3>) {
/// let derefed_ptr = ptr.deref(&memory); /// let derefed_ptr = ptr.deref(&mut ctx, &memory);
/// let mut inner_val: V3 = derefed_ptr.read().expect("pointer in bounds"); /// let mut inner_val: V3 = derefed_ptr.read().expect("pointer in bounds");
/// println!("Got {:?} from Wasm memory address 0x{:X}", inner_val, ptr.offset()); /// println!("Got {:?} from Wasm memory address 0x{:X}", inner_val, ptr.offset());
/// // update the value being pointed to /// // update the value being pointed to

View File

@@ -108,7 +108,7 @@ mod sys {
let instance = Instance::new(&mut ctx, &module, &imports)?; let instance = Instance::new(&mut ctx, &module, &imports)?;
{ {
fn sum(ctx: ContextMut<()>, a: i32, b: i32) -> i32 { fn sum(_ctx: ContextMut<()>, a: i32, b: i32) -> i32 {
a + b a + b
} }
let sum_func = Function::new_native(&mut ctx, sum); let sum_func = Function::new_native(&mut ctx, sum);

View File

@@ -273,12 +273,13 @@ impl<F: Fn(&Operator) -> u64 + Send + Sync> FunctionMiddleware for FunctionMeter
/// ///
/// ```rust /// ```rust
/// use wasmer::Instance; /// use wasmer::Instance;
/// use wasmer::AsContextMut;
/// use wasmer_middlewares::metering::{get_remaining_points, MeteringPoints}; /// use wasmer_middlewares::metering::{get_remaining_points, MeteringPoints};
/// ///
/// /// Check whether the instance can continue to run based on the /// /// Check whether the instance can continue to run based on the
/// /// number of remaining points. /// /// number of remaining points.
/// fn can_continue_to_run(instance: &Instance) -> bool { /// fn can_continue_to_run(ctx: &mut impl AsContextMut, instance: &Instance) -> bool {
/// matches!(get_remaining_points(instance), MeteringPoints::Remaining(points) if points > 0) /// matches!(get_remaining_points(&mut ctx.as_context_mut(), instance), MeteringPoints::Remaining(points) if points > 0)
/// } /// }
/// ``` /// ```
pub fn get_remaining_points(ctx: &mut impl AsContextMut, instance: &Instance) -> MeteringPoints { pub fn get_remaining_points(ctx: &mut impl AsContextMut, instance: &Instance) -> MeteringPoints {
@@ -320,15 +321,15 @@ pub fn get_remaining_points(ctx: &mut impl AsContextMut, instance: &Instance) ->
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// use wasmer::Instance; /// use wasmer::{AsContextMut, Instance};
/// use wasmer_middlewares::metering::set_remaining_points; /// use wasmer_middlewares::metering::set_remaining_points;
/// ///
/// fn update_remaining_points(instance: &Instance) { /// fn update_remaining_points(ctx: &mut impl AsContextMut, instance: &Instance) {
/// // The new limit. /// // The new limit.
/// let new_limit = 10; /// let new_limit = 10;
/// ///
/// // Update the remaining points to the `new_limit`. /// // Update the remaining points to the `new_limit`.
/// set_remaining_points(instance, new_limit); /// set_remaining_points(&mut ctx.as_context_mut(), instance, new_limit);
/// } /// }
/// ``` /// ```
pub fn set_remaining_points(ctx: &mut impl AsContextMut, instance: &Instance, points: u64) { pub fn set_remaining_points(ctx: &mut impl AsContextMut, instance: &Instance, points: u64) {
@@ -383,6 +384,7 @@ mod tests {
#[test] #[test]
fn get_remaining_points_works() { fn get_remaining_points_works() {
use wasmer::Context as WasmerContext;
let metering = Arc::new(Metering::new(10, cost_function)); let metering = Arc::new(Metering::new(10, cost_function));
let mut compiler_config = Cranelift::default(); let mut compiler_config = Cranelift::default();
compiler_config.push_middleware(metering); compiler_config.push_middleware(metering);

View File

@@ -143,7 +143,6 @@ mod native {
/// ///
/// ``` /// ```
/// use wasmer_types::{NativeWasmType, Type}; /// use wasmer_types::{NativeWasmType, Type};
/// use wasmer_types::{NativeWasmType, Type};
/// ///
/// let wasm_type = i32::WASM_TYPE; /// let wasm_type = i32::WASM_TYPE;
/// assert_eq!(wasm_type, Type::I32); /// assert_eq!(wasm_type, Type::I32);

View File

@@ -371,7 +371,7 @@ impl GlobalType {
/// Create a new Global variable /// Create a new Global variable
/// # Usage: /// # Usage:
/// ``` /// ```
/// use wasmer_types::{GlobalType, Type, Mutability, Value}; /// use wasmer_types::{GlobalType, Type, Mutability};
/// ///
/// // An I32 constant global /// // An I32 constant global
/// let global = GlobalType::new(Type::I32, Mutability::Const); /// let global = GlobalType::new(Type::I32, Mutability::Const);