diff options
| author | Brian Anderson <banderson@mozilla.com> | 2012-06-07 23:36:34 -0700 |
|---|---|---|
| committer | Brian Anderson <banderson@mozilla.com> | 2012-06-08 10:58:46 -0700 |
| commit | f12adcbf930122ef6d98790b53d80d511dc62406 (patch) | |
| tree | 0c18abe5f064553a623b4331b6143f6e35d10cfc /src/libcore | |
| parent | 75d9ec100b8f1483e18877b53d578c2aea265480 (diff) | |
| download | rust-f12adcbf930122ef6d98790b53d80d511dc62406.tar.gz rust-f12adcbf930122ef6d98790b53d80d511dc62406.zip | |
core: Add unsafe::transmute
Like reinterpret_cast + forget
Diffstat (limited to 'src/libcore')
| -rw-r--r-- | src/libcore/unsafe.rs | 29 |
1 files changed, 28 insertions, 1 deletions
diff --git a/src/libcore/unsafe.rs b/src/libcore/unsafe.rs index 7b99727b48a..0c8261f71ad 100644 --- a/src/libcore/unsafe.rs +++ b/src/libcore/unsafe.rs @@ -1,6 +1,6 @@ #[doc = "Unsafe operations"]; -export reinterpret_cast, forget; +export reinterpret_cast, forget, transmute; #[abi = "rust-intrinsic"] native mod rusti { @@ -27,6 +27,20 @@ reinterpret_cast on managed pointer types. #[inline(always)] unsafe fn forget<T>(-thing: T) { rusti::forget(thing); } +#[doc = " +Transform a value of one type into a value of another type. +Both types must have the same size and alignment. + +# Example + + assert transmute(\"L\") == [76u8, 0u8]; +"] +unsafe fn transmute<L, G>(-thing: L) -> G { + let newthing = reinterpret_cast(thing); + forget(thing); + ret newthing; +} + #[cfg(test)] mod tests { @@ -34,4 +48,17 @@ mod tests { fn test_reinterpret_cast() unsafe { assert reinterpret_cast(1) == 1u; } + + #[test] + fn test_transmute() unsafe { + let x = @1; + let x: *int = transmute(x); + assert *x == 1; + let _x: @int = transmute(x); + } + + #[test] + fn test_transmute2() unsafe { + assert transmute("L") == [76u8, 0u8]; + } } |
