-
Notifications
You must be signed in to change notification settings - Fork 275
Rust: Provide a trait method to (optionally) control resource allocation #1625
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
cpetig
wants to merge
6
commits into
bytecodealliance:main
Choose a base branch
from
cpetig:resource_arena
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
16a9bd9
Resource allocation override option
cpetig e9cc4e3
custom resource allocation
cpetig 4263a8b
cut the dirty tricks out of the arena
cpetig 582cc11
hide that it is an Option (typedef), put underscore to the end
cpetig 2ae4a31
Some review comments of mine and refactorings
alexcrichton dc970be
Fix doc example
alexcrichton File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -23,4 +23,5 @@ crate::generate!({ | |
| } | ||
| } | ||
| "#, | ||
| runtime_path: "crate::rt", // only needed for this in-crate example. | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| //! Helper traits, types, and utilities for managing resources in the component | ||
| //! model. | ||
|
|
||
| /// A trait implemented by all resources that a component might export. | ||
| /// | ||
| /// This is an implementation detail primarily for the code generated by | ||
| /// exported resources. The primary purpose of this trait is to serve as an | ||
| /// abstraction for the in-memory storage of a resource. | ||
| pub trait Resource: Sized + 'static { | ||
| /// The type which is actually stored in-memory for this resource. | ||
| /// | ||
| /// By default this is `Option<T>`. | ||
| type Rep: ResourceRep<Self>; | ||
| } | ||
|
|
||
| impl<T: 'static> Resource for T { | ||
| type Rep = Option<T>; | ||
| } | ||
|
|
||
| /// A trait used to define how to access the underlying data `T` from an | ||
| /// in-memory representation. | ||
| /// | ||
| /// This is used as a bound on the [`Resource::Rep`] associated type which is in | ||
| /// turn used to access data within a resources. | ||
| pub unsafe trait ResourceRep<T> { | ||
| /// Creates a new instance of `Self` which wraps the provided data. | ||
| fn rep_new(inner: T) -> Self; | ||
|
|
||
| /// Acquires `&T` from a raw pointer to `Self`. | ||
| unsafe fn rep_as_ref<'a>(ptr: *const Self) -> &'a T; | ||
|
|
||
| /// Acquires `&mut T` from a raw pointer to `Self`. | ||
| unsafe fn rep_as_mut<'a>(ptr: *mut Self) -> &'a mut T; | ||
|
|
||
| /// Takes the value out of `Self` at the provided pointer. | ||
| /// | ||
| /// Note that `ptr` will later be deallocated meaning that it must not run | ||
| /// the destructor of `T` after this method is called. This is guaranteed to | ||
| /// be called at most once, however. Additionally after calling this method | ||
| /// it's guaranteed that the `rep_as_*` method above will not be called. | ||
| unsafe fn rep_take<'a>(ptr: *mut Self) -> T; | ||
| } | ||
|
|
||
| unsafe impl<T> ResourceRep<T> for Option<T> { | ||
| fn rep_new(inner: T) -> Option<T> { | ||
| Some(inner) | ||
| } | ||
| unsafe fn rep_as_ref<'a>(ptr: *const Option<T>) -> &'a T { | ||
| unsafe { (*ptr).as_ref().unwrap() } | ||
| } | ||
| unsafe fn rep_as_mut<'a>(ptr: *mut Option<T>) -> &'a mut T { | ||
| unsafe { (*ptr).as_mut().unwrap() } | ||
| } | ||
| unsafe fn rep_take(ptr: *mut Option<T>) -> T { | ||
| unsafe { (*ptr).take().unwrap() } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| include!(env!("BINDINGS")); | ||
|
|
||
| use crate::test::arena_allocated_resources::to_test::Thing; | ||
|
|
||
| struct Component; | ||
|
|
||
| export!(Component); | ||
|
|
||
| impl Guest for Component { | ||
| fn run() { | ||
| let thing1 = Thing::new(3); | ||
| let thing2 = Thing::new(5); | ||
| assert_eq!(3, thing1.get()); | ||
| assert_eq!(5, thing2.get()); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| include!(env!("BINDINGS")); | ||
|
|
||
| use crate::exports::test::arena_allocated_resources::to_test::{Guest, GuestThing}; | ||
|
|
||
| export!(Component); | ||
|
|
||
| struct Component; | ||
|
|
||
| impl Guest for Component { | ||
| type Thing = MyThing; | ||
| } | ||
|
|
||
| mod arena { | ||
|
|
||
| use core::sync::atomic::{AtomicUsize, Ordering}; | ||
| use core::{cell::UnsafeCell, mem::MaybeUninit}; | ||
|
|
||
| /// A simple no_std arena allocator for fixed-size allocations. | ||
| /// | ||
| /// The arena allocates items of type T sequentially from a pre-allocated buffer | ||
| /// and does not support individual deallocation. Memory is reclaimed | ||
| /// only when the entire arena is reset. | ||
| pub struct Arena<T, const SIZE: usize> { | ||
| buffer: [UnsafeCell<MaybeUninit<T>>; SIZE], | ||
| offset: AtomicUsize, | ||
| } | ||
|
|
||
| // Element allocation is atomic and elements are exclusively handed out after allocation, | ||
| // so the arena can be send to other threads and simultaneosly accessed by multiple threads | ||
| unsafe impl<T: Sync, const SIZE: usize> Sync for Arena<T, SIZE> {} | ||
| unsafe impl<T: Send, const SIZE: usize> Send for Arena<T, SIZE> {} | ||
|
|
||
| impl<T: Default, const SIZE: usize> Arena<T, SIZE> { | ||
| pub const fn new() -> Self { | ||
| Self { | ||
| buffer: [const { UnsafeCell::new(MaybeUninit::uninit()) }; SIZE], | ||
| offset: AtomicUsize::new(0), | ||
| } | ||
| } | ||
|
|
||
| /// Allocates space for a single item of type T. | ||
| /// Returns a mutable reference to the allocated memory, or None if there's insufficient space. | ||
| pub fn alloc_one(&self) -> Option<&mut T> { | ||
| // short circuit the exhausted state (don't increment if full) | ||
| if self.offset.load(Ordering::Relaxed) >= SIZE { | ||
| None | ||
| } else { | ||
| // now try to allocate for real | ||
| let pos = self.offset.fetch_add(1, Ordering::Acquire); | ||
| if pos >= SIZE { | ||
| // now self.offset is already beyond SIZE, reduce our increment and return none | ||
| self.offset.fetch_sub(1, Ordering::Release); | ||
| None | ||
| } else { | ||
| let ptr = self.buffer[pos].get(); | ||
| // SAFETY: we demand exclusive ownership of the item in the arena | ||
| let uninit = unsafe { &mut *ptr }; | ||
| Some(uninit.write(Default::default())) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| use arena::Arena; | ||
|
|
||
| #[derive(Clone)] | ||
| struct MyThing { | ||
| contents: u32, | ||
| } | ||
|
|
||
| static ARENA: Arena<Option<MyThing>, 4> = Arena::new(); | ||
|
|
||
| impl GuestThing for MyThing { | ||
| fn new(v: u32) -> MyThing { | ||
| MyThing { contents: v } | ||
| } | ||
|
|
||
| fn get(&self) -> u32 { | ||
| self.contents | ||
| } | ||
|
|
||
| unsafe fn resource_into_raw_(val: Self::Rep) -> *mut Self::Rep { | ||
| val.and_then(|v| { | ||
| ARENA.alloc_one().map(|x| { | ||
| *x = Some(v); | ||
| x as *mut _ | ||
| }) | ||
| }) | ||
| .unwrap_or(core::ptr::null_mut()) | ||
| } | ||
|
|
||
| unsafe fn resource_from_raw_(handle: *mut Self::Rep) -> Self::Rep { | ||
| unsafe { &mut *handle }.take() | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.