]> git.lizzy.rs Git - rust.git/blob - src/libcore/ty.rs
Rename all raw pointers as necessary
[rust.git] / src / libcore / ty.rs
1 // Copyright 2012-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 //! Types dealing with unsafe actions.
12
13 use kinds::marker;
14
15 /// Unsafe type that wraps a type T and indicates unsafe interior operations on the
16 /// wrapped type. Types with an `Unsafe<T>` field are considered to have an *unsafe
17 /// interior*. The Unsafe type is the only legal way to obtain aliasable data that is
18 /// considered mutable. In general, transmuting an &T type into an &mut T is considered
19 /// undefined behavior.
20 ///
21 /// Although it is possible to put an Unsafe<T> into static item, it is not permitted to
22 /// take the address of the static item if the item is not declared as mutable. This rule
23 /// exists because immutable static items are stored in read-only memory, and thus any
24 /// attempt to mutate their interior can cause segfaults. Immutable static items containing
25 /// Unsafe<T> instances are still useful as read-only initializers, however, so we do not
26 /// forbid them altogether.
27 ///
28 /// Types like `Cell` and `RefCell` use this type to wrap their internal data.
29 ///
30 /// Unsafe doesn't opt-out from any kind, instead, types with an `Unsafe` interior
31 /// are expected to opt-out from kinds themselves.
32 ///
33 /// # Example:
34 ///
35 /// ```rust
36 /// use std::ty::Unsafe;
37 /// use std::kinds::marker;
38 ///
39 /// struct NotThreadSafe<T> {
40 ///     value: Unsafe<T>,
41 ///     marker1: marker::NoShare
42 /// }
43 /// ```
44 ///
45 /// **NOTE:** Unsafe<T> fields are public to allow static initializers. It is not recommended
46 /// to access its fields directly, `get` should be used instead.
47 #[lang="unsafe"]
48 pub struct Unsafe<T> {
49     /// Wrapped value
50     pub value: T,
51
52     /// Invariance marker
53     pub marker1: marker::InvariantType<T>
54 }
55
56 impl<T> Unsafe<T> {
57
58     /// Static constructor
59     pub fn new(value: T) -> Unsafe<T> {
60         Unsafe{value: value, marker1: marker::InvariantType}
61     }
62
63     /// Gets a mutable pointer to the wrapped value
64     #[inline]
65     pub unsafe fn get(&self) -> *mut T { &self.value as *const T as *mut T }
66
67     /// Unwraps the value
68     #[inline]
69     pub unsafe fn unwrap(self) -> T { self.value }
70 }