]> git.proxmox.com Git - rustc.git/blob - src/libcore/raw.rs
43535ddd1d5c5f7ff9b27d7bb8d91919e805e4b5
[rustc.git] / src / libcore / raw.rs
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)]
12 #![unstable(feature = "raw")]
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
21 use clone::Clone;
22 use marker::Copy;
23 use mem;
24
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 /// ```
52 /// # #![feature(raw)]
53 /// use std::raw::{self, Repr};
54 ///
55 /// let slice: &[u16] = &[1, 2, 3, 4];
56 ///
57 /// let repr: raw::Slice<u16> = slice.repr();
58 /// println!("data pointer = {:?}, length = {}", repr.data, repr.len);
59 /// ```
60 #[repr(C)]
61 pub struct Slice<T> {
62 pub data: *const T,
63 pub len: usize,
64 }
65
66 impl<T> Copy for Slice<T> {}
67 impl<T> Clone for Slice<T> {
68 fn clone(&self) -> Slice<T> { *self }
69 }
70
71 /// The representation of a trait object like `&SomeTrait`.
72 ///
73 /// This struct has the same layout as types like `&SomeTrait` and
74 /// `Box<AnotherTrait>`. The [Trait Objects chapter of the
75 /// Book][moreinfo] contains more details about the precise nature of
76 /// these internals.
77 ///
78 /// [moreinfo]: ../../book/trait-objects.html#representation
79 ///
80 /// `TraitObject` is guaranteed to match layouts, but it is not the
81 /// type of trait objects (e.g. the fields are not directly accessible
82 /// on a `&SomeTrait`) nor does it control that layout (changing the
83 /// definition will not change the layout of a `&SomeTrait`). It is
84 /// only designed to be used by unsafe code that needs to manipulate
85 /// the low-level details.
86 ///
87 /// There is no `Repr` implementation for `TraitObject` because there
88 /// is no way to refer to all trait objects generically, so the only
89 /// way to create values of this type is with functions like
90 /// `std::mem::transmute`. Similarly, the only way to create a true
91 /// trait object from a `TraitObject` value is with `transmute`.
92 ///
93 /// Synthesizing a trait object with mismatched types—one where the
94 /// vtable does not correspond to the type of the value to which the
95 /// data pointer points—is highly likely to lead to undefined
96 /// behaviour.
97 ///
98 /// # Examples
99 ///
100 /// ```
101 /// # #![feature(raw)]
102 /// use std::mem;
103 /// use std::raw;
104 ///
105 /// // an example trait
106 /// trait Foo {
107 /// fn bar(&self) -> i32;
108 /// }
109 /// impl Foo for i32 {
110 /// fn bar(&self) -> i32 {
111 /// *self + 1
112 /// }
113 /// }
114 ///
115 /// let value: i32 = 123;
116 ///
117 /// // let the compiler make a trait object
118 /// let object: &Foo = &value;
119 ///
120 /// // look at the raw representation
121 /// let raw_object: raw::TraitObject = unsafe { mem::transmute(object) };
122 ///
123 /// // the data pointer is the address of `value`
124 /// assert_eq!(raw_object.data as *const i32, &value as *const _);
125 ///
126 ///
127 /// let other_value: i32 = 456;
128 ///
129 /// // construct a new object, pointing to a different `i32`, being
130 /// // careful to use the `i32` vtable from `object`
131 /// let synthesized: &Foo = unsafe {
132 /// mem::transmute(raw::TraitObject {
133 /// data: &other_value as *const _ as *mut (),
134 /// vtable: raw_object.vtable
135 /// })
136 /// };
137 ///
138 /// // it should work just like we constructed a trait object out of
139 /// // `other_value` directly
140 /// assert_eq!(synthesized.bar(), 457);
141 /// ```
142 #[repr(C)]
143 #[derive(Copy, Clone)]
144 pub struct TraitObject {
145 pub data: *mut (),
146 pub vtable: *mut (),
147 }
148
149 /// This trait is meant to map equivalences between raw structs and their
150 /// corresponding rust values.
151 pub unsafe trait Repr<T> {
152 /// This function "unwraps" a rust value (without consuming it) into its raw
153 /// struct representation. This can be used to read/write different values
154 /// for the struct. This is a safe method because by default it does not
155 /// enable write-access to the fields of the return value in safe code.
156 #[inline]
157 fn repr(&self) -> T { unsafe { mem::transmute_copy(&self) } }
158 }
159
160 unsafe impl<T> Repr<Slice<T>> for [T] {}
161 unsafe impl Repr<Slice<u8>> for str {}