Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a variable borrow for 'static?

Tags:

rust

lifetime

In vulkano, to create a CPUAccessibleBuffer you need give it some data and the CPUAccessibleBuffer::from_data function requires the data to have the 'static lifetime.

I have some data in &[u8] array (created at runtime) that I would like to pass to that function.

However, it errors with this message

argument requires that `data` is borrowed for `'static`

So how can I make the lifetime of the data 'static ?

like image 636
little_monkey Avatar asked Apr 25 '26 04:04

little_monkey


2 Answers

You should use CpuAccessibleBuffer::from_iter instead, it does the same thing but does not require the collection to be Copy or 'static:

let data: &[u8] = todo!();

let _ = CpuAccessibleBuffer::from_iter(
    device,
    usage,
    host_cached,
    data.iter().copied(), // <--- pass like so
);

Or if you actually have a Vec<u8>, you can pass it directly:

let data: Vec<u8> = todo!();

let _ = CpuAccessibleBuffer::from_iter(
    device,
    usage,
    host_cached,
    data, // <--- pass like so
);
like image 159
kmdreko Avatar answered Apr 29 '26 01:04

kmdreko


If you really must create the data at runtime, and you really need to last for 'static, then you can use one of the memory leaking methods such as Box::leak or Vec::leak to deliberately leak a heap allocation and ensure it is never freed.

While leaking memory is normally something one avoids, in this case it's actually a sensible thing to do. If the data must live forever then leaking it is actually the correct thing to do, semantically speaking. You don't want the memory to be freed, not ever, which is exactly what happens when memory is leaked.

Example:

fn require_static_data(data: &'static [u8]) {
    unimplemented!()
}

fn main() {
    let data = vec![1, 2, 3, 4];
    require_static_data(data.leak());
}

Playground

That said, really think over the reallys I led with. Make sure you understand why the code you're calling wants 'static data and ask yourself why your data isn't already 'static.

  • Is it possible to create the data at compile time? Rust has a powerful build time macro system. It's possible, for example, to use include_bytes! to read in a file and do some processing on it before it's embedded into your executable.

  • Is there another API you can use, another function call you're not seeing that doesn't require 'static?

(These questions aren't for you specifically, but for anyone who comes across this Q&A in the future.)

like image 42
John Kugelman Avatar answered Apr 29 '26 00:04

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!