]> git.proxmox.com Git - rustc.git/blob - src/libcore/ptr.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / libcore / ptr.rs
1 // Copyright 2012-2014 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 // FIXME: talk about offset, copy_memory, copy_nonoverlapping_memory
12
13 //! Raw, unsafe pointers, `*const T`, and `*mut T`.
14 //!
15 //! *[See also the pointer primitive types](../../std/primitive.pointer.html).*
16
17 #![stable(feature = "rust1", since = "1.0.0")]
18
19 use clone::Clone;
20 use intrinsics;
21 use ops::{CoerceUnsized, Deref};
22 use fmt;
23 use hash;
24 use option::Option::{self, Some, None};
25 use marker::{Copy, PhantomData, Send, Sized, Sync, Unsize};
26 use mem;
27 use nonzero::NonZero;
28
29 use cmp::{PartialEq, Eq, Ord, PartialOrd};
30 use cmp::Ordering::{self, Less, Equal, Greater};
31
32 // FIXME #19649: intrinsic docs don't render, so these have no docs :(
33
34 #[stable(feature = "rust1", since = "1.0.0")]
35 pub use intrinsics::copy_nonoverlapping;
36
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub use intrinsics::copy;
39
40 #[stable(feature = "rust1", since = "1.0.0")]
41 pub use intrinsics::write_bytes;
42
43 #[stable(feature = "drop_in_place", since = "1.8.0")]
44 pub use intrinsics::drop_in_place;
45
46 /// Creates a null raw pointer.
47 ///
48 /// # Examples
49 ///
50 /// ```
51 /// use std::ptr;
52 ///
53 /// let p: *const i32 = ptr::null();
54 /// assert!(p.is_null());
55 /// ```
56 #[inline]
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub const fn null<T>() -> *const T { 0 as *const T }
59
60 /// Creates a null mutable raw pointer.
61 ///
62 /// # Examples
63 ///
64 /// ```
65 /// use std::ptr;
66 ///
67 /// let p: *mut i32 = ptr::null_mut();
68 /// assert!(p.is_null());
69 /// ```
70 #[inline]
71 #[stable(feature = "rust1", since = "1.0.0")]
72 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
73
74 /// Swaps the values at two mutable locations of the same type, without
75 /// deinitializing either. They may overlap, unlike `mem::swap` which is
76 /// otherwise equivalent.
77 ///
78 /// # Safety
79 ///
80 /// This is only unsafe because it accepts a raw pointer.
81 #[inline]
82 #[stable(feature = "rust1", since = "1.0.0")]
83 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
84 // Give ourselves some scratch space to work with
85 let mut tmp: T = mem::uninitialized();
86
87 // Perform the swap
88 copy_nonoverlapping(x, &mut tmp, 1);
89 copy(y, x, 1); // `x` and `y` may overlap
90 copy_nonoverlapping(&tmp, y, 1);
91
92 // y and t now point to the same thing, but we need to completely forget `tmp`
93 // because it's no longer relevant.
94 mem::forget(tmp);
95 }
96
97 /// Replaces the value at `dest` with `src`, returning the old
98 /// value, without dropping either.
99 ///
100 /// # Safety
101 ///
102 /// This is only unsafe because it accepts a raw pointer.
103 /// Otherwise, this operation is identical to `mem::replace`.
104 #[inline]
105 #[stable(feature = "rust1", since = "1.0.0")]
106 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
107 mem::swap(&mut *dest, &mut src); // cannot overlap
108 src
109 }
110
111 /// Reads the value from `src` without moving it. This leaves the
112 /// memory in `src` unchanged.
113 ///
114 /// # Safety
115 ///
116 /// Beyond accepting a raw pointer, this is unsafe because it semantically
117 /// moves the value out of `src` without preventing further usage of `src`.
118 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
119 /// `src` is not used before the data is overwritten again (e.g. with `write`,
120 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
121 /// because it will attempt to drop the value previously at `*src`.
122 #[inline(always)]
123 #[stable(feature = "rust1", since = "1.0.0")]
124 pub unsafe fn read<T>(src: *const T) -> T {
125 let mut tmp: T = mem::uninitialized();
126 copy_nonoverlapping(src, &mut tmp, 1);
127 tmp
128 }
129
130 #[allow(missing_docs)]
131 #[inline(always)]
132 #[unstable(feature = "filling_drop",
133 reason = "may play a larger role in std::ptr future extensions",
134 issue = "5016")]
135 pub unsafe fn read_and_drop<T>(dest: *mut T) -> T {
136 // Copy the data out from `dest`:
137 let tmp = read(&*dest);
138
139 // Now mark `dest` as dropped:
140 write_bytes(dest, mem::POST_DROP_U8, 1);
141
142 tmp
143 }
144
145 /// Overwrites a memory location with the given value without reading or
146 /// dropping the old value.
147 ///
148 /// # Safety
149 ///
150 /// This operation is marked unsafe because it accepts a raw pointer.
151 ///
152 /// It does not drop the contents of `dst`. This is safe, but it could leak
153 /// allocations or resources, so care must be taken not to overwrite an object
154 /// that should be dropped.
155 ///
156 /// This is appropriate for initializing uninitialized memory, or overwriting
157 /// memory that has previously been `read` from.
158 #[inline]
159 #[stable(feature = "rust1", since = "1.0.0")]
160 pub unsafe fn write<T>(dst: *mut T, src: T) {
161 intrinsics::move_val_init(&mut *dst, src)
162 }
163
164 /// Performs a volatile read of the value from `src` without moving it. This
165 /// leaves the memory in `src` unchanged.
166 ///
167 /// Volatile operations are intended to act on I/O memory, and are guaranteed
168 /// to not be elided or reordered by the compiler across other volatile
169 /// operations.
170 ///
171 /// # Notes
172 ///
173 /// Rust does not currently have a rigorously and formally defined memory model,
174 /// so the precise semantics of what "volatile" means here is subject to change
175 /// over time. That being said, the semantics will almost always end up pretty
176 /// similar to [C11's definition of volatile][c11].
177 ///
178 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
179 ///
180 /// # Safety
181 ///
182 /// Beyond accepting a raw pointer, this is unsafe because it semantically
183 /// moves the value out of `src` without preventing further usage of `src`.
184 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
185 /// `src` is not used before the data is overwritten again (e.g. with `write`,
186 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
187 /// because it will attempt to drop the value previously at `*src`.
188 #[inline]
189 #[stable(feature = "volatile", since = "1.9.0")]
190 pub unsafe fn read_volatile<T>(src: *const T) -> T {
191 intrinsics::volatile_load(src)
192 }
193
194 /// Performs a volatile write of a memory location with the given value without
195 /// reading or dropping the old value.
196 ///
197 /// Volatile operations are intended to act on I/O memory, and are guaranteed
198 /// to not be elided or reordered by the compiler across other volatile
199 /// operations.
200 ///
201 /// # Notes
202 ///
203 /// Rust does not currently have a rigorously and formally defined memory model,
204 /// so the precise semantics of what "volatile" means here is subject to change
205 /// over time. That being said, the semantics will almost always end up pretty
206 /// similar to [C11's definition of volatile][c11].
207 ///
208 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
209 ///
210 /// # Safety
211 ///
212 /// This operation is marked unsafe because it accepts a raw pointer.
213 ///
214 /// It does not drop the contents of `dst`. This is safe, but it could leak
215 /// allocations or resources, so care must be taken not to overwrite an object
216 /// that should be dropped.
217 ///
218 /// This is appropriate for initializing uninitialized memory, or overwriting
219 /// memory that has previously been `read` from.
220 #[inline]
221 #[stable(feature = "volatile", since = "1.9.0")]
222 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
223 intrinsics::volatile_store(dst, src);
224 }
225
226 #[lang = "const_ptr"]
227 impl<T: ?Sized> *const T {
228 /// Returns true if the pointer is null.
229 ///
230 /// # Examples
231 ///
232 /// Basic usage:
233 ///
234 /// ```
235 /// let s: &str = "Follow the rabbit";
236 /// let ptr: *const u8 = s.as_ptr();
237 /// assert!(!ptr.is_null());
238 /// ```
239 #[stable(feature = "rust1", since = "1.0.0")]
240 #[inline]
241 pub fn is_null(self) -> bool where T: Sized {
242 self == null()
243 }
244
245 /// Returns `None` if the pointer is null, or else returns a reference to
246 /// the value wrapped in `Some`.
247 ///
248 /// # Safety
249 ///
250 /// While this method and its mutable counterpart are useful for
251 /// null-safety, it is important to note that this is still an unsafe
252 /// operation because the returned value could be pointing to invalid
253 /// memory.
254 ///
255 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
256 /// not necessarily reflect the actual lifetime of the data.
257 ///
258 /// # Examples
259 ///
260 /// Basic usage:
261 ///
262 /// ```ignore
263 /// let val: *const u8 = &10u8 as *const u8;
264 ///
265 /// unsafe {
266 /// if let Some(val_back) = val.as_ref() {
267 /// println!("We got back the value: {}!", val_back);
268 /// }
269 /// }
270 /// ```
271 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
272 #[inline]
273 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
274 if self.is_null() {
275 None
276 } else {
277 Some(&*self)
278 }
279 }
280
281 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
282 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
283 ///
284 /// # Safety
285 ///
286 /// Both the starting and resulting pointer must be either in bounds or one
287 /// byte past the end of an allocated object. If either pointer is out of
288 /// bounds or arithmetic overflow occurs then
289 /// any further use of the returned value will result in undefined behavior.
290 ///
291 /// # Examples
292 ///
293 /// Basic usage:
294 ///
295 /// ```
296 /// let s: &str = "123";
297 /// let ptr: *const u8 = s.as_ptr();
298 ///
299 /// unsafe {
300 /// println!("{}", *ptr.offset(1) as char);
301 /// println!("{}", *ptr.offset(2) as char);
302 /// }
303 /// ```
304 #[stable(feature = "rust1", since = "1.0.0")]
305 #[inline]
306 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
307 intrinsics::offset(self, count)
308 }
309 }
310
311 #[lang = "mut_ptr"]
312 impl<T: ?Sized> *mut T {
313 /// Returns true if the pointer is null.
314 ///
315 /// # Examples
316 ///
317 /// Basic usage:
318 ///
319 /// ```
320 /// let mut s = [1, 2, 3];
321 /// let ptr: *mut u32 = s.as_mut_ptr();
322 /// assert!(!ptr.is_null());
323 /// ```
324 #[stable(feature = "rust1", since = "1.0.0")]
325 #[inline]
326 pub fn is_null(self) -> bool where T: Sized {
327 self == null_mut()
328 }
329
330 /// Returns `None` if the pointer is null, or else returns a reference to
331 /// the value wrapped in `Some`.
332 ///
333 /// # Safety
334 ///
335 /// While this method and its mutable counterpart are useful for
336 /// null-safety, it is important to note that this is still an unsafe
337 /// operation because the returned value could be pointing to invalid
338 /// memory.
339 ///
340 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
341 /// not necessarily reflect the actual lifetime of the data.
342 ///
343 /// # Examples
344 ///
345 /// Basic usage:
346 ///
347 /// ```ignore
348 /// let val: *mut u8 = &mut 10u8 as *mut u8;
349 ///
350 /// unsafe {
351 /// if let Some(val_back) = val.as_ref() {
352 /// println!("We got back the value: {}!", val_back);
353 /// }
354 /// }
355 /// ```
356 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
357 #[inline]
358 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
359 if self.is_null() {
360 None
361 } else {
362 Some(&*self)
363 }
364 }
365
366 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
367 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
368 ///
369 /// # Safety
370 ///
371 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
372 /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
373 /// the pointer is used.
374 ///
375 /// # Examples
376 ///
377 /// Basic usage:
378 ///
379 /// ```
380 /// let mut s = [1, 2, 3];
381 /// let ptr: *mut u32 = s.as_mut_ptr();
382 ///
383 /// unsafe {
384 /// println!("{}", *ptr.offset(1));
385 /// println!("{}", *ptr.offset(2));
386 /// }
387 /// ```
388 #[stable(feature = "rust1", since = "1.0.0")]
389 #[inline]
390 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
391 intrinsics::offset(self, count) as *mut T
392 }
393
394 /// Returns `None` if the pointer is null, or else returns a mutable
395 /// reference to the value wrapped in `Some`.
396 ///
397 /// # Safety
398 ///
399 /// As with `as_ref`, this is unsafe because it cannot verify the validity
400 /// of the returned pointer, nor can it ensure that the lifetime `'a`
401 /// returned is indeed a valid lifetime for the contained data.
402 ///
403 /// # Examples
404 ///
405 /// Basic usage:
406 ///
407 /// ```
408 /// let mut s = [1, 2, 3];
409 /// let ptr: *mut u32 = s.as_mut_ptr();
410 /// ```
411 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
412 #[inline]
413 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> where T: Sized {
414 if self.is_null() {
415 None
416 } else {
417 Some(&mut *self)
418 }
419 }
420 }
421
422 // Equality for pointers
423 #[stable(feature = "rust1", since = "1.0.0")]
424 impl<T: ?Sized> PartialEq for *const T {
425 #[inline]
426 fn eq(&self, other: &*const T) -> bool { *self == *other }
427 }
428
429 #[stable(feature = "rust1", since = "1.0.0")]
430 impl<T: ?Sized> Eq for *const T {}
431
432 #[stable(feature = "rust1", since = "1.0.0")]
433 impl<T: ?Sized> PartialEq for *mut T {
434 #[inline]
435 fn eq(&self, other: &*mut T) -> bool { *self == *other }
436 }
437
438 #[stable(feature = "rust1", since = "1.0.0")]
439 impl<T: ?Sized> Eq for *mut T {}
440
441 #[stable(feature = "rust1", since = "1.0.0")]
442 impl<T: ?Sized> Clone for *const T {
443 #[inline]
444 fn clone(&self) -> *const T {
445 *self
446 }
447 }
448
449 #[stable(feature = "rust1", since = "1.0.0")]
450 impl<T: ?Sized> Clone for *mut T {
451 #[inline]
452 fn clone(&self) -> *mut T {
453 *self
454 }
455 }
456
457 // Impls for function pointers
458 macro_rules! fnptr_impls_safety_abi {
459 ($FnTy: ty, $($Arg: ident),*) => {
460 #[stable(feature = "rust1", since = "1.0.0")]
461 impl<Ret, $($Arg),*> Clone for $FnTy {
462 #[inline]
463 fn clone(&self) -> Self {
464 *self
465 }
466 }
467
468 #[stable(feature = "fnptr_impls", since = "1.4.0")]
469 impl<Ret, $($Arg),*> PartialEq for $FnTy {
470 #[inline]
471 fn eq(&self, other: &Self) -> bool {
472 *self as usize == *other as usize
473 }
474 }
475
476 #[stable(feature = "fnptr_impls", since = "1.4.0")]
477 impl<Ret, $($Arg),*> Eq for $FnTy {}
478
479 #[stable(feature = "fnptr_impls", since = "1.4.0")]
480 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
481 #[inline]
482 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
483 (*self as usize).partial_cmp(&(*other as usize))
484 }
485 }
486
487 #[stable(feature = "fnptr_impls", since = "1.4.0")]
488 impl<Ret, $($Arg),*> Ord for $FnTy {
489 #[inline]
490 fn cmp(&self, other: &Self) -> Ordering {
491 (*self as usize).cmp(&(*other as usize))
492 }
493 }
494
495 #[stable(feature = "fnptr_impls", since = "1.4.0")]
496 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
497 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
498 state.write_usize(*self as usize)
499 }
500 }
501
502 #[stable(feature = "fnptr_impls", since = "1.4.0")]
503 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
504 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
505 fmt::Pointer::fmt(&(*self as *const ()), f)
506 }
507 }
508
509 #[stable(feature = "fnptr_impls", since = "1.4.0")]
510 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
511 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
512 fmt::Pointer::fmt(&(*self as *const ()), f)
513 }
514 }
515 }
516 }
517
518 macro_rules! fnptr_impls_args {
519 ($($Arg: ident),*) => {
520 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
521 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
522 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
523 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
524 }
525 }
526
527 fnptr_impls_args! { }
528 fnptr_impls_args! { A }
529 fnptr_impls_args! { A, B }
530 fnptr_impls_args! { A, B, C }
531 fnptr_impls_args! { A, B, C, D }
532 fnptr_impls_args! { A, B, C, D, E }
533 fnptr_impls_args! { A, B, C, D, E, F }
534 fnptr_impls_args! { A, B, C, D, E, F, G }
535 fnptr_impls_args! { A, B, C, D, E, F, G, H }
536 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
537 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
538 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
539 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
540
541 // Comparison for pointers
542 #[stable(feature = "rust1", since = "1.0.0")]
543 impl<T: ?Sized> Ord for *const T {
544 #[inline]
545 fn cmp(&self, other: &*const T) -> Ordering {
546 if self < other {
547 Less
548 } else if self == other {
549 Equal
550 } else {
551 Greater
552 }
553 }
554 }
555
556 #[stable(feature = "rust1", since = "1.0.0")]
557 impl<T: ?Sized> PartialOrd for *const T {
558 #[inline]
559 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
560 Some(self.cmp(other))
561 }
562
563 #[inline]
564 fn lt(&self, other: &*const T) -> bool { *self < *other }
565
566 #[inline]
567 fn le(&self, other: &*const T) -> bool { *self <= *other }
568
569 #[inline]
570 fn gt(&self, other: &*const T) -> bool { *self > *other }
571
572 #[inline]
573 fn ge(&self, other: &*const T) -> bool { *self >= *other }
574 }
575
576 #[stable(feature = "rust1", since = "1.0.0")]
577 impl<T: ?Sized> Ord for *mut T {
578 #[inline]
579 fn cmp(&self, other: &*mut T) -> Ordering {
580 if self < other {
581 Less
582 } else if self == other {
583 Equal
584 } else {
585 Greater
586 }
587 }
588 }
589
590 #[stable(feature = "rust1", since = "1.0.0")]
591 impl<T: ?Sized> PartialOrd for *mut T {
592 #[inline]
593 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
594 Some(self.cmp(other))
595 }
596
597 #[inline]
598 fn lt(&self, other: &*mut T) -> bool { *self < *other }
599
600 #[inline]
601 fn le(&self, other: &*mut T) -> bool { *self <= *other }
602
603 #[inline]
604 fn gt(&self, other: &*mut T) -> bool { *self > *other }
605
606 #[inline]
607 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
608 }
609
610 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
611 /// of this wrapper owns the referent. This in turn implies that the
612 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
613 /// `*mut T` (which conveys no particular ownership semantics). It
614 /// also implies that the referent of the pointer should not be
615 /// modified without a unique path to the `Unique` reference. Useful
616 /// for building abstractions like `Vec<T>` or `Box<T>`, which
617 /// internally use raw pointers to manage the memory that they own.
618 #[allow(missing_debug_implementations)]
619 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
620 issue = "27730")]
621 pub struct Unique<T: ?Sized> {
622 pointer: NonZero<*const T>,
623 // NOTE: this marker has no consequences for variance, but is necessary
624 // for dropck to understand that we logically own a `T`.
625 //
626 // For details, see:
627 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
628 _marker: PhantomData<T>,
629 }
630
631 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
632 /// reference is unaliased. Note that this aliasing invariant is
633 /// unenforced by the type system; the abstraction using the
634 /// `Unique` must enforce it.
635 #[unstable(feature = "unique", issue = "27730")]
636 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
637
638 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
639 /// reference is unaliased. Note that this aliasing invariant is
640 /// unenforced by the type system; the abstraction using the
641 /// `Unique` must enforce it.
642 #[unstable(feature = "unique", issue = "27730")]
643 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
644
645 #[unstable(feature = "unique", issue = "27730")]
646 impl<T: ?Sized> Unique<T> {
647 /// Creates a new `Unique`.
648 ///
649 /// # Safety
650 ///
651 /// `ptr` must be non-null.
652 pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
653 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
654 }
655
656 /// Dereferences the content.
657 pub unsafe fn get(&self) -> &T {
658 &**self.pointer
659 }
660
661 /// Mutably dereferences the content.
662 pub unsafe fn get_mut(&mut self) -> &mut T {
663 &mut ***self
664 }
665 }
666
667 #[unstable(feature = "unique", issue = "27730")]
668 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
669
670 #[unstable(feature = "unique", issue= "27730")]
671 impl<T:?Sized> Deref for Unique<T> {
672 type Target = *mut T;
673
674 #[inline]
675 fn deref(&self) -> &*mut T {
676 unsafe { mem::transmute(&*self.pointer) }
677 }
678 }
679
680 #[stable(feature = "rust1", since = "1.0.0")]
681 impl<T> fmt::Pointer for Unique<T> {
682 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
683 fmt::Pointer::fmt(&*self.pointer, f)
684 }
685 }
686
687 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
688 /// of this wrapper has shared ownership of the referent. Useful for
689 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
690 /// use raw pointers to manage the memory that they own.
691 #[allow(missing_debug_implementations)]
692 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
693 issue = "27730")]
694 pub struct Shared<T: ?Sized> {
695 pointer: NonZero<*const T>,
696 // NOTE: this marker has no consequences for variance, but is necessary
697 // for dropck to understand that we logically own a `T`.
698 //
699 // For details, see:
700 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
701 _marker: PhantomData<T>,
702 }
703
704 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
705 // NB: This impl is unnecessary, but should provide better error messages.
706 #[unstable(feature = "shared", issue = "27730")]
707 impl<T: ?Sized> !Send for Shared<T> { }
708
709 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
710 // NB: This impl is unnecessary, but should provide better error messages.
711 #[unstable(feature = "shared", issue = "27730")]
712 impl<T: ?Sized> !Sync for Shared<T> { }
713
714 #[unstable(feature = "shared", issue = "27730")]
715 impl<T: ?Sized> Shared<T> {
716 /// Creates a new `Shared`.
717 ///
718 /// # Safety
719 ///
720 /// `ptr` must be non-null.
721 pub unsafe fn new(ptr: *mut T) -> Self {
722 Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
723 }
724 }
725
726 #[unstable(feature = "shared", issue = "27730")]
727 impl<T: ?Sized> Clone for Shared<T> {
728 fn clone(&self) -> Self {
729 *self
730 }
731 }
732
733 #[unstable(feature = "shared", issue = "27730")]
734 impl<T: ?Sized> Copy for Shared<T> { }
735
736 #[unstable(feature = "shared", issue = "27730")]
737 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
738
739 #[unstable(feature = "shared", issue = "27730")]
740 impl<T: ?Sized> Deref for Shared<T> {
741 type Target = *mut T;
742
743 #[inline]
744 fn deref(&self) -> &*mut T {
745 unsafe { mem::transmute(&*self.pointer) }
746 }
747 }
748
749 #[unstable(feature = "shared", issue = "27730")]
750 impl<T> fmt::Pointer for Shared<T> {
751 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
752 fmt::Pointer::fmt(&*self.pointer, f)
753 }
754 }