Skip to content
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

Add SingleBox::leak to provide access to a &'static mut #8

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

jannic
Copy link

@jannic jannic commented Nov 5, 2024

The use case for the added function is to provide a &'static mut.
So this

    static mut BUFFER: [u8; 1024] = [0u8; 1024];
    let buf: &mut [u8; 1024] = unsafe { &mut BUFFER };

can be replaced by

   static BUFFER: AllocSingle<[u8; 1024]> = AllocSingle::new();
   let buf: &mut [u8; 1024] = BUFFER.alloc([0u8; 1024]).unwrap().leak();

This avoids using unsafe in user code. In case the second line is accidentally run twice, it'll cause a panic instead of UB. (And even the panic could be avoided by replacing unwrap by appropriate error handling.)

Actual situation where this would be useful: rp-rs/rp-hal#864

Please let me know if there's an easier way to do the same!

@thejpster
Copy link

Won't your example stack allocate the array in order to move it into the 'heap' allocation?

@jannic
Copy link
Author

jannic commented Nov 5, 2024

Won't your example stack allocate the array in order to move it into the 'heap' allocation?

Yes, of course. Could be avoided by using alloc_const_val.

///
/// This will prevent T's destructor from being called.
pub fn leak<'b>(self) -> &'b mut T
where T: 'b,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this extra 'b lifetime? If 'a is 'static already, won't returning &'a mut T already get you the static lifetime?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not 100% sure!
If 'a is 'static and we want a &'static mut T, then sure, that would work.
But what if we actually need a shorter lifetime? I guess it's still fine because &'a T is covariant in 'a, https://doc.rust-lang.org/reference/subtyping.html#variance, so any &'a T is a subtype of &'static T for all lifetimes 'a?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants