Skip to main content

RealmScope

Struct RealmScope 

Source
pub struct RealmScope<R> { /* private fields */ }
Expand description

The active identity of a guest realm.

A generation distinguishes successive guest instances that use the same realm identifier. Hosts should advance it when an instance is replaced.

Implementations§

Source§

impl<R> RealmScope<R>

Source

pub const fn new(realm: R, generation: u64) -> Self

Create a scope for the currently active guest instance.

Examples found in repository?
examples/native_document.rs (line 40)
39    fn scope(&self) -> RealmScope<u64> {
40        RealmScope::new(1, 1)
41    }
More examples
Hide additional examples
examples/native_host.rs (line 98)
96fn main() {
97    let mut guest = Guest {
98        scope: RealmScope::new(Rc::new(1), 1),
99        root: None,
100        intrinsic: None,
101        calls: 0,
102    };
103    guest
104        .register_intrinsic("increment", 1, |_, arguments| {
105            arguments
106                .first()
107                .copied()
108                .map(|value| value + 1)
109                .ok_or("missing argument")
110        })
111        .expect("register compiled intrinsic");
112    let callback = guest.retain_callback(&7).expect("retain callback");
113    assert_eq!(
114        NativeHost::invoke_retained_callback(&mut guest, &callback, &[5]),
115        Ok(6)
116    );
117    let foreign = RetainedCallback::new(Rc::new(2), 1, Rc::clone(callback.callback()));
118    assert_eq!(
119        NativeHost::invoke_retained_callback(&mut guest, &foreign, &[5]),
120        Err(NativeCallbackError::StaleCallback)
121    );
122    assert_eq!(
123        guest.calls, 1,
124        "foreign scope must not enter guest dispatch"
125    );
126    guest.release_callback(&callback).expect("release callback");
127    assert!(NativeHost::invoke_retained_callback(&mut guest, &callback.clone(), &[5]).is_err());
128    assert_eq!(guest.calls, 1, "release must revoke cloned tokens");
129    let next = guest.retain_callback(&7).expect("retain next callback");
130    guest.scope = RealmScope::new(Rc::clone(guest.scope.realm()), 2);
131    assert_eq!(
132        NativeHost::invoke_retained_callback(&mut guest, &next, &[5]),
133        Err(NativeCallbackError::StaleCallback)
134    );
135    assert_eq!(
136        guest.calls, 1,
137        "stale generation must not enter guest dispatch"
138    );
139    println!("typed native dispatch, root release, realm and generation checks passed");
140}
Source

pub const fn realm(&self) -> &R

The identifier of the realm.

Examples found in repository?
examples/native_host.rs (line 34)
27    fn retain_callback(&mut self, value: &i64) -> Result<Callback, Self::Error> {
28        if *value != 7 || self.root.is_some() {
29            return Err("not an available callback");
30        }
31        let root = Rc::new(());
32        self.root = Some(Rc::clone(&root));
33        Ok(RetainedCallback::new(
34            Rc::clone(self.scope.realm()),
35            self.scope.generation(),
36            root,
37        ))
38    }
39
40    fn release_callback(&mut self, callback: &Callback) -> Result<(), Self::Error> {
41        if !self.current(callback) {
42            return Err("callback unavailable");
43        }
44        self.root = None;
45        Ok(())
46    }
47
48    fn register_intrinsic(
49        &mut self,
50        name: &'static str,
51        arity: u8,
52        callback: NativeIntrinsic<Self>,
53    ) -> Result<(), Self::Error> {
54        if name != "increment" || arity != 1 {
55            return Err("invalid intrinsic");
56        }
57        self.intrinsic = Some(callback);
58        Ok(())
59    }
60
61    fn invoke_retained_callback(
62        &mut self,
63        callback: &Callback,
64        arguments: &[i64],
65    ) -> Result<i64, Self::Error> {
66        if !self.current(callback) {
67            return Err("callback unavailable");
68        }
69        self.calls += 1;
70        self.intrinsic.ok_or("intrinsic unavailable")?(self, arguments)
71    }
72}
73
74impl Guest {
75    fn current(&self, callback: &Callback) -> bool {
76        callback.is_current_in(&self.scope)
77            && self
78                .root
79                .as_ref()
80                .is_some_and(|root| Rc::ptr_eq(root, callback.callback()))
81    }
82}
83
84impl NativeHost for Guest {
85    type Guest = Self;
86
87    fn guest(&self) -> &Self {
88        self
89    }
90
91    fn guest_mut(&mut self) -> &mut Self {
92        self
93    }
94}
95
96fn main() {
97    let mut guest = Guest {
98        scope: RealmScope::new(Rc::new(1), 1),
99        root: None,
100        intrinsic: None,
101        calls: 0,
102    };
103    guest
104        .register_intrinsic("increment", 1, |_, arguments| {
105            arguments
106                .first()
107                .copied()
108                .map(|value| value + 1)
109                .ok_or("missing argument")
110        })
111        .expect("register compiled intrinsic");
112    let callback = guest.retain_callback(&7).expect("retain callback");
113    assert_eq!(
114        NativeHost::invoke_retained_callback(&mut guest, &callback, &[5]),
115        Ok(6)
116    );
117    let foreign = RetainedCallback::new(Rc::new(2), 1, Rc::clone(callback.callback()));
118    assert_eq!(
119        NativeHost::invoke_retained_callback(&mut guest, &foreign, &[5]),
120        Err(NativeCallbackError::StaleCallback)
121    );
122    assert_eq!(
123        guest.calls, 1,
124        "foreign scope must not enter guest dispatch"
125    );
126    guest.release_callback(&callback).expect("release callback");
127    assert!(NativeHost::invoke_retained_callback(&mut guest, &callback.clone(), &[5]).is_err());
128    assert_eq!(guest.calls, 1, "release must revoke cloned tokens");
129    let next = guest.retain_callback(&7).expect("retain next callback");
130    guest.scope = RealmScope::new(Rc::clone(guest.scope.realm()), 2);
131    assert_eq!(
132        NativeHost::invoke_retained_callback(&mut guest, &next, &[5]),
133        Err(NativeCallbackError::StaleCallback)
134    );
135    assert_eq!(
136        guest.calls, 1,
137        "stale generation must not enter guest dispatch"
138    );
139    println!("typed native dispatch, root release, realm and generation checks passed");
140}
Source

pub const fn generation(&self) -> u64

The generation of the guest instance in this realm.

Examples found in repository?
examples/native_host.rs (line 35)
27    fn retain_callback(&mut self, value: &i64) -> Result<Callback, Self::Error> {
28        if *value != 7 || self.root.is_some() {
29            return Err("not an available callback");
30        }
31        let root = Rc::new(());
32        self.root = Some(Rc::clone(&root));
33        Ok(RetainedCallback::new(
34            Rc::clone(self.scope.realm()),
35            self.scope.generation(),
36            root,
37        ))
38    }

Trait Implementations§

Source§

impl<R: Clone> Clone for RealmScope<R>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<R: Copy> Copy for RealmScope<R>

Source§

impl<R: Debug> Debug for RealmScope<R>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<R: Eq> Eq for RealmScope<R>

Source§

impl<R: Hash> Hash for RealmScope<R>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<R: PartialEq> PartialEq for RealmScope<R>

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<R: PartialEq> StructuralPartialEq for RealmScope<R>

Auto Trait Implementations§

§

impl<R> Forget for RealmScope<R>

§

impl<R> Freeze for RealmScope<R>
where R: Freeze,

§

impl<R> Move for RealmScope<R>

§

impl<R> RefUnwindSafe for RealmScope<R>
where R: RefUnwindSafe,

§

impl<R> Send for RealmScope<R>
where R: Send,

§

impl<R> Sync for RealmScope<R>
where R: Sync,

§

impl<R> Unpin for RealmScope<R>
where R: Unpin,

§

impl<R> UnsafeUnpin for RealmScope<R>
where R: UnsafeUnpin,

§

impl<R> UnwindSafe for RealmScope<R>
where R: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> MaybeBoxed<Box<T>> for T

Source§

fn maybe_boxed(self) -> Box<T>

Convert
Source§

impl<T> MaybeBoxed<T> for T

Source§

fn maybe_boxed(self) -> T

Convert
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.