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