Path: blob/main/crates/environ/src/scopevec.rs
1691 views
use crate::prelude::*;1use core::cell::RefCell;23/// Small data structure to help extend the lifetime of a slice to a higher4/// scope.5///6/// This is currently used during component translation where translation in7/// general works on a borrowed slice which contains all input modules, but8/// generated adapter modules for components don't live within the original9/// slice but the data structures are much easier if the dynamically generated10/// adapter modules live for the same lifetime as the original input slice. To11/// solve this problem this `ScopeVec` helper is used to move ownership of a12/// `Vec<T>` to a higher scope in the program, then borrowing the slice from13/// that scope.14pub struct ScopeVec<T> {15data: RefCell<Vec<Box<[T]>>>,16}1718impl<T> ScopeVec<T> {19/// Creates a new blank scope.20pub fn new() -> ScopeVec<T> {21ScopeVec {22data: Default::default(),23}24}2526/// Transfers ownership of `data` into this scope and then yields the slice27/// back to the caller.28///29/// The original data will be deallocated when `self` is dropped.30pub fn push(&self, data: Vec<T>) -> &mut [T] {31let data: Box<[T]> = data.into();32let len = data.len();3334let mut storage = self.data.borrow_mut();35storage.push(data);36let ptr = storage.last_mut().unwrap().as_mut_ptr();3738// This should be safe for a few reasons:39//40// * The returned pointer on the heap that `data` owns. Despite moving41// `data` around it doesn't actually move the slice itself around, so42// the pointer returned should be valid (and length).43//44// * The lifetime of the returned pointer is connected to the lifetime45// of `self`. This reflects how when `self` is destroyed the `data` is46// destroyed as well, or otherwise the returned slice will be valid47// for as long as `self` is valid since `self` owns the original data48// at that point.49//50// * This function was given ownership of `data` so it should be safe to51// hand back a mutable reference. Once placed within a `ScopeVec` the52// data is never mutated so the caller will enjoy exclusive access to53// the slice of the original vec.54//55// This all means that it should be safe to return a mutable slice of56// all of `data` after the data has been pushed onto our internal list.57unsafe { core::slice::from_raw_parts_mut(ptr, len) }58}5960/// Iterate over items in this `ScopeVec`, consuming ownership.61pub fn into_iter(self) -> impl ExactSizeIterator<Item = Box<[T]>> {62self.data.into_inner().into_iter()63}64}6566#[cfg(test)]67mod tests {68use super::ScopeVec;69use crate::prelude::*;7071#[test]72fn smoke() {73let scope = ScopeVec::new();74let a = scope.push(Vec::new());75let b = scope.push(vec![1, 2, 3]);76let c = scope.push(vec![4, 5, 6]);77assert_eq!(a.len(), 0);78b[0] = 4;79c[2] = 5;80assert_eq!(a, []);81assert_eq!(b, [4, 2, 3]);82assert_eq!(c, [4, 5, 5]);83}84}858687