Skip to content

Commit f12adcb

Browse files
committed
core: Add unsafe::transmute
Like reinterpret_cast + forget
1 parent 75d9ec1 commit f12adcb

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

src/libcore/unsafe.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#[doc = "Unsafe operations"];
22

3-
export reinterpret_cast, forget;
3+
export reinterpret_cast, forget, transmute;
44

55
#[abi = "rust-intrinsic"]
66
native mod rusti {
@@ -27,11 +27,38 @@ reinterpret_cast on managed pointer types.
2727
#[inline(always)]
2828
unsafe fn forget<T>(-thing: T) { rusti::forget(thing); }
2929

30+
#[doc = "
31+
Transform a value of one type into a value of another type.
32+
Both types must have the same size and alignment.
33+
34+
# Example
35+
36+
assert transmute(\"L\") == [76u8, 0u8];
37+
"]
38+
unsafe fn transmute<L, G>(-thing: L) -> G {
39+
let newthing = reinterpret_cast(thing);
40+
forget(thing);
41+
ret newthing;
42+
}
43+
3044
#[cfg(test)]
3145
mod tests {
3246

3347
#[test]
3448
fn test_reinterpret_cast() unsafe {
3549
assert reinterpret_cast(1) == 1u;
3650
}
51+
52+
#[test]
53+
fn test_transmute() unsafe {
54+
let x = @1;
55+
let x: *int = transmute(x);
56+
assert *x == 1;
57+
let _x: @int = transmute(x);
58+
}
59+
60+
#[test]
61+
fn test_transmute2() unsafe {
62+
assert transmute("L") == [76u8, 0u8];
63+
}
3764
}

0 commit comments

Comments
 (0)