Closed
Description
Perhaps we should add an intrinsic like:
fn zero<T: POD>() -> T
that basically fills T
with zeros. This is perfectly safe for POD types. Of course, we don't have a POD kind yet, but that's a separate issue I guess. This is particularly useful in C interop, where you often have functions with out-params that otherwise need to be initialized by hand.
We could also add an intrinsic like
fn undefined<T: POD>() -> T
which would just leave the data uninitialized. This would be more efficient but less safe in some sense. Though restricting it to POD at least preserves memory safety, more-or-less.
The idea is you'd write something like:
struct FooResult { /*something POD*/ }
extern mod c_library { fn foo(p: &mut FooResult) -> bool; }
fn foo() -> FooResult {
let result = defined();
if !c_library::foo(&mut result) { fail; }
return result;
}
Activity
nikomatsakis commentedon Sep 12, 2012
Here is an example that came up on IRC, but it comes up regularly: http://pastebin.com/v534PrDW. Sscroll to the final function.
jruderman commentedon Sep 12, 2012
In C++, POD structs can contain pointers.
jruderman commentedon Sep 12, 2012
SpiderMonkey contains a similar
PodZero
function:https://bugzilla.mozilla.org/show_bug.cgi?id=551276
http://hg.mozilla.org/mozilla-central/annotate/87f6f50a0207/js/src/jsutil.h#l177
jruderman commentedon Sep 12, 2012
I'd prefer to declare the C function as taking a
&write FooResult
, so the type-checker knows it can be uninitialized before the call and will be initialized after the call.nikomatsakis commentedon Sep 12, 2012
Yeah, I wrote "more-or-less" because I figured
*T
would be POD, but not@T
or~T
, but of course we don't make any guarantees about unsafe ptrs.nikomatsakis commentedon Nov 5, 2012
So, it turns out that this exists! (the intrinsic
init()
) However, it does not check for POD and nor is it considered unsafe. Bad. See https://github.com/mozilla/rust/blob/master/src/libcore/comm.rs#L297. I'm gonna repurpose this issue to address its shortcomings.nikomatsakis commentedon Nov 5, 2012
Oh, never mind,
init()
seems to fill with zero. It should still be unsafe.init()
intrinsic is unsafe #3920uninit
intrinsic. Use incore::vec
#4204Aatch commentedon May 10, 2013
Closed by #6354
Auto merge of rust-lang#3471 - RalfJung:blocked, r=RalfJung