Hacker News new | past | comments | ask | show | jobs | submit login

I’m not a Rust programmer, but I’m curious, and I’m wondering if someone could explain how their generational-box crate works? [1]

I understand that it’s some kind of arena allocation, but I don’t understand how they support copying without copying, or how this is safe:

> Internally, generational-box creates an arena of generational RefCell's that are recycled when the owner is dropped. You can think of the cells as something like &'static RefCell<Box<dyn Any>> with a generational check to make recycling a cell easier to debug. Then GenerationalBox's are Copy because the &'static pointer is Copy

Like okay, you can create a pointer to static data, but what if it’s something that doesn’t have a static lifetime?

[1] https://crates.io/crates/generational-box




We are copying the reference to the data, not the data itself. The reference to the data lasts for the lifetime of the program. Generational box lets you insert data that last for shorter than the lifetime of the program (as long as that data contains no references). Once you drop the data you inserted, we reuse the box for other allocations.

It uses a very similar approach to a generational arena but with boxes instead of a centralized arena (to avoid locking issues). If you try to access the Copy reference to the data after it has been dropped, it will fail with a nice error message


Thanks. I’m wondering if this allows for non-static data at all? Maybe it has to be either static or copyable?


All data you insert into a generational box needs to be allowed to last for the 'static lifetime (have no internal temporary pointers). You cannot insert something like &'a str into a generational box


I am not familiar with this crate, but I am with Rust, here’s my take:

Copy is a specific thing in Rust, it means that if a type implements the Copy trait, it can be copied via a memcpy, that is, it’s like a “shallow” copy as opposed to a “deep” copy.

So they’re not “copying without copying”, they’re letting you treat a non-Copy type as a Copy type, in my understanding.

> what if it’s something that doesn’t have a static lifetime?

The read me says it requires static content so the answer is “you can’t do that.”


Could you use position-independent internal references (relative pointers) to make data copyable? Does Rust have good support for that?


Rust does not have native support for relative pointers, so you'd have to hack that together with unsafe. It's not generally done.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: