]> git.proxmox.com Git - rustc.git/blame - src/libcore/raw.rs
Imported Upstream version 1.3.0+dfsg1
[rustc.git] / src / libcore / raw.rs
CommitLineData
1a4d82fc
JJ
1// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11#![allow(missing_docs)]
62682a34 12#![unstable(feature = "raw")]
1a4d82fc
JJ
13
14//! Contains struct definitions for the layout of compiler built-in types.
15//!
16//! They can be used as targets of transmutes in unsafe code for manipulating
17//! the raw representations directly.
18//!
19//! Their definition should always match the ABI defined in `rustc::back::abi`.
20
c34b1796 21use clone::Clone;
1a4d82fc
JJ
22use marker::Copy;
23use mem;
24
85aaf69f
SL
25/// The representation of a slice like `&[T]`.
26///
27/// This struct is guaranteed to have the layout of types like `&[T]`,
28/// `&str`, and `Box<[T]>`, but is not the type of such slices
29/// (e.g. the fields are not directly accessible on a `&[T]`) nor does
30/// it control that layout (changing the definition will not change
31/// the layout of a `&[T]`). It is only designed to be used by unsafe
32/// code that needs to manipulate the low-level details.
33///
34/// However, it is not recommended to use this type for such code,
35/// since there are alternatives which may be safer:
36///
37/// - Creating a slice from a data pointer and length can be done with
38/// `std::slice::from_raw_parts` or `std::slice::from_raw_parts_mut`
39/// instead of `std::mem::transmute`ing a value of type `Slice`.
40/// - Extracting the data pointer and length from a slice can be
41/// performed with the `as_ptr` (or `as_mut_ptr`) and `len`
42/// methods.
43///
44/// If one does decide to convert a slice value to a `Slice`, the
45/// `Repr` trait in this module provides a method for a safe
46/// conversion from `&[T]` (and `&str`) to a `Slice`, more type-safe
47/// than a call to `transmute`.
48///
49/// # Examples
50///
51/// ```
c1a9b12d
SL
52/// #![feature(raw)]
53///
85aaf69f
SL
54/// use std::raw::{self, Repr};
55///
56/// let slice: &[u16] = &[1, 2, 3, 4];
57///
58/// let repr: raw::Slice<u16> = slice.repr();
59/// println!("data pointer = {:?}, length = {}", repr.data, repr.len);
60/// ```
1a4d82fc
JJ
61#[repr(C)]
62pub struct Slice<T> {
63 pub data: *const T,
85aaf69f 64 pub len: usize,
1a4d82fc
JJ
65}
66
67impl<T> Copy for Slice<T> {}
c34b1796
AL
68impl<T> Clone for Slice<T> {
69 fn clone(&self) -> Slice<T> { *self }
1a4d82fc
JJ
70}
71
85aaf69f
SL
72/// The representation of a trait object like `&SomeTrait`.
73///
74/// This struct has the same layout as types like `&SomeTrait` and
9346a6ac 75/// `Box<AnotherTrait>`. The [Trait Objects chapter of the
85aaf69f
SL
76/// Book][moreinfo] contains more details about the precise nature of
77/// these internals.
78///
9346a6ac 79/// [moreinfo]: ../../book/trait-objects.html#representation
85aaf69f
SL
80///
81/// `TraitObject` is guaranteed to match layouts, but it is not the
82/// type of trait objects (e.g. the fields are not directly accessible
83/// on a `&SomeTrait`) nor does it control that layout (changing the
d9579d0f 84/// definition will not change the layout of a `&SomeTrait`). It is
85aaf69f
SL
85/// only designed to be used by unsafe code that needs to manipulate
86/// the low-level details.
87///
88/// There is no `Repr` implementation for `TraitObject` because there
89/// is no way to refer to all trait objects generically, so the only
90/// way to create values of this type is with functions like
91/// `std::mem::transmute`. Similarly, the only way to create a true
92/// trait object from a `TraitObject` value is with `transmute`.
93///
94/// Synthesizing a trait object with mismatched types—one where the
95/// vtable does not correspond to the type of the value to which the
96/// data pointer points—is highly likely to lead to undefined
97/// behaviour.
98///
99/// # Examples
100///
101/// ```
c1a9b12d
SL
102/// #![feature(raw)]
103///
85aaf69f
SL
104/// use std::mem;
105/// use std::raw;
106///
107/// // an example trait
108/// trait Foo {
109/// fn bar(&self) -> i32;
110/// }
111/// impl Foo for i32 {
112/// fn bar(&self) -> i32 {
113/// *self + 1
114/// }
115/// }
116///
117/// let value: i32 = 123;
118///
119/// // let the compiler make a trait object
120/// let object: &Foo = &value;
121///
122/// // look at the raw representation
123/// let raw_object: raw::TraitObject = unsafe { mem::transmute(object) };
124///
125/// // the data pointer is the address of `value`
126/// assert_eq!(raw_object.data as *const i32, &value as *const _);
127///
128///
129/// let other_value: i32 = 456;
130///
131/// // construct a new object, pointing to a different `i32`, being
132/// // careful to use the `i32` vtable from `object`
133/// let synthesized: &Foo = unsafe {
134/// mem::transmute(raw::TraitObject {
135/// data: &other_value as *const _ as *mut (),
136/// vtable: raw_object.vtable
137/// })
138/// };
1a4d82fc 139///
85aaf69f
SL
140/// // it should work just like we constructed a trait object out of
141/// // `other_value` directly
142/// assert_eq!(synthesized.bar(), 457);
143/// ```
1a4d82fc 144#[repr(C)]
c34b1796 145#[derive(Copy, Clone)]
1a4d82fc
JJ
146pub struct TraitObject {
147 pub data: *mut (),
148 pub vtable: *mut (),
149}
150
151/// This trait is meant to map equivalences between raw structs and their
152/// corresponding rust values.
85aaf69f 153pub unsafe trait Repr<T> {
1a4d82fc
JJ
154 /// This function "unwraps" a rust value (without consuming it) into its raw
155 /// struct representation. This can be used to read/write different values
156 /// for the struct. This is a safe method because by default it does not
157 /// enable write-access to the fields of the return value in safe code.
158 #[inline]
159 fn repr(&self) -> T { unsafe { mem::transmute_copy(&self) } }
160}
161
85aaf69f
SL
162unsafe impl<T> Repr<Slice<T>> for [T] {}
163unsafe impl Repr<Slice<u8>> for str {}