wasmtime_environ/
scopevec.rs

1use std::cell::RefCell;
2
3/// Small data structure to help extend the lifetime of a slice to a higher
4/// scope.
5///
6/// This is currently used during component translation where translation in
7/// general works on a borrowed slice which contains all input modules, but
8/// generated adapter modules for components don't live within the original
9/// slice but the data structures are much easier if the dynamically generated
10/// adapter modules live for the same lifetime as the original input slice. To
11/// solve this problem this `ScopeVec` helper is used to move ownership of a
12/// `Vec<T>` to a higher scope in the program, then borrowing the slice from
13/// that scope.
14pub struct ScopeVec<T> {
15    data: RefCell<Vec<Box<[T]>>>,
16}
17
18impl<T> ScopeVec<T> {
19    /// Creates a new blank scope.
20    pub fn new() -> ScopeVec<T> {
21        ScopeVec {
22            data: Default::default(),
23        }
24    }
25
26    /// Transfers ownership of `data` into this scope and then yields the slice
27    /// back to the caller.
28    ///
29    /// The original data will be deallocated when `self` is dropped.
30    pub fn push(&self, data: Vec<T>) -> &mut [T] {
31        let mut data: Box<[T]> = data.into();
32        let ptr = data.as_mut_ptr();
33        let len = data.len();
34        self.data.borrow_mut().push(data);
35
36        // This should be safe for a few reasons:
37        //
38        // * The returned pointer on the heap that `data` owns. Despite moving
39        //   `data` around it doesn't actually move the slice itself around, so
40        //   the pointer returned should be valid (and length).
41        //
42        // * The lifetime of the returned pointer is connected to the lifetime
43        //   of `self`. This reflects how when `self` is destroyed the `data` is
44        //   destroyed as well, or otherwise the returned slice will be valid
45        //   for as long as `self` is valid since `self` owns the original data
46        //   at that point.
47        //
48        // * This function was given ownership of `data` so it should be safe to
49        //   hand back a mutable reference. Once placed within a `ScopeVec` the
50        //   data is never mutated so the caller will enjoy exclusive access to
51        //   the slice of the original vec.
52        //
53        // This all means that it should be safe to return a mutable slice of
54        // all of `data` after the data has been pushed onto our internal list.
55        unsafe { std::slice::from_raw_parts_mut(ptr, len) }
56    }
57}