Is it possible to write this code so that the return type isn't a T? I don't
think it's possible to have a function that returns T but takes no parameters
of type T in a way that is truly safe. As long as only you use
md_from_metadata, and you are careful about how you use it, you can probably
avoid any errors, but these sorts of errors are exactly what a type system is
supposed to protect you from in the first place. More problems are likely to
come if other people start using md_from_metadata.
Normally, the right place for reinterpret_cast is when you're writing really
low-level code that can't really be done safely anyway. For example, at least
at one point (and possibly still now), task.rs would construct new stack frames
and this required casting data into raw bytes to store on the stack.
The fact that you called this debug_metadata suggests you might be in an
appropriate place to use reinterpret_cast, but if so, try not to export
md_from_metadata, and if at all possible, try to write you code so you don't
need reinterpret_cast.
-Eric
On Nov 10, 2011, at 10:42 AM, Josh Matthews wrote:
> I have written the following code:
>
> tag debug_metadata {
> file_metadata(@metadata<file_md>);
> compile_unit_metadata(@metadata<compile_unit_md>);
> subprogram_metadata(@metadata<subprogram_md>);
> }
>
> fn md_from_metadata<T>(val: debug_metadata) -> T unsafe {
> alt val {
> file_metadata(md) { unsafe::reinterpret_cast(md) }
> compile_unit_metadata(md) { unsafe::reinterpret_cast(md) }
> subprogram_metadata(md) { unsafe::reinterpret_cast(md) }
> }
> }
>
> Assume that I know precisely what type I am extracting at any given
> point when I call md_from_metadata, so I call the specific typed
> version that gives me the correct output (ie. I am never actually
> casting a value to the incorrect type). My Principles of Software
> Engineering prof would surely call this "bad zen", but using
> md_from_metadata in this way makes the calling code noticeably cleaner
> in my eyes. Are there any safety concerns that come with using
> reinterpret_cast in this way, or is the code simply a harmless hack?
>
> Cheers,
> Josh
> _______________________________________________
> Rust-dev mailing list
> [email protected]
> https://mail.mozilla.org/listinfo/rust-dev
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev