Lokathor/bytemuck

Why Pod requires T to be copy?

ente76 opened this issue · 3 comments

Currently Pod requires Copy for T, which isn't too cool for my project. I want to transform some structs (mostly 4x u32 up to 10x u32) into &[u8]. Since those structs are heavily passed along functions, I want to avoid in having accidental copies occurring. For that reason I would rather fall back to manual cloning (which so far can be fully avoided) than implementing copy on the struct. Any way you could implement a feature that disables the copy requirement?

I'm afraid that such a change would be a very big one, and cause unacceptable levels of increased danger of things going wrong. Even just as an opt-in feature, I think it's too much.

What's mostly actually being required is "not Drop", because Pod lets you make a value from nowhere so the type better not have any Drop code. Technically since it's an unsafe trait that Copy requirement could just be torn out and additional unsafe requirements could be written into the docs. If it had been like that from the start maybe that would be fine, but at this point I wouldn't feel comfortable making such a significant change.

This sounds like something you should solve within your crate by just carefully looking at all your function signatures and watching that they accept references as often as possible. As long as it's always a reference when passed between functions things should be fine.

This sounds like something you should solve within your crate by just carefully looking at all your function signatures and watching that they accept references as often as possible. As long as it's always a reference when passed between functions things should be fine.

What? We are working in Rust for a reason. Actually I just need the one-way transformation. I am not sure which checks are required to be safe, but I don't have so many structs to transform and they are all pure multiples of 32 bit fields. I will write those 2 lines myself from scratch. I feel better this way than to miss a &-reference in a function call and loose performance due to unnecessary allocations.

Thanks anyway!

Edit: fixed the quote

I hope you're aware that passing by reference can also give performance losses depending on the situation.

But yes, it should be simple enough to write an as_u32_slice function on your intended types.