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.
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.
11 // FIXME: talk about offset, copy_memory, copy_nonoverlapping_memory
13 //! Operations on unsafe pointers, `*const T`, and `*mut T`.
15 //! Working with unsafe pointers in Rust is uncommon,
16 //! typically limited to a few patterns.
18 //! Use the [`null` function](fn.null.html) to create null pointers,
19 //! the [`is_null`](trait.RawPtr.html#tymethod.is_null)
20 //! and [`is_not_null`](trait.RawPtr.html#method.is_not_null)
21 //! methods of the [`RawPtr` trait](trait.RawPtr.html) to check for null.
22 //! The `RawPtr` trait is imported by the prelude, so `is_null` etc.
23 //! work everywhere. The `RawPtr` also defines the `offset` method,
26 //! # Common ways to create unsafe pointers
28 //! ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
31 //! let my_num: int = 10;
32 //! let my_num_ptr: *const int = &my_num;
33 //! let mut my_speed: int = 88;
34 //! let my_speed_ptr: *mut int = &mut my_speed;
37 //! This does not take ownership of the original allocation
38 //! and requires no resource management later,
39 //! but you must not use the pointer after its lifetime.
41 //! ## 2. Transmute an owned box (`Box<T>`).
43 //! The `transmute` function takes, by value, whatever it's given
44 //! and returns it as whatever type is requested, as long as the
45 //! types are the same size. Because `Box<T>` and `*mut T` have the same
46 //! representation they can be trivially,
47 //! though unsafely, transformed from one type to the other.
53 //! let my_num: Box<int> = box 10;
54 //! let my_num: *const int = mem::transmute(my_num);
55 //! let my_speed: Box<int> = box 88;
56 //! let my_speed: *mut int = mem::transmute(my_speed);
58 //! // By taking ownership of the original `Box<T>` though
59 //! // we are obligated to transmute it back later to be destroyed.
60 //! drop(mem::transmute::<_, Box<int>>(my_speed));
61 //! drop(mem::transmute::<_, Box<int>>(my_num));
65 //! Note that here the call to `drop` is for clarity - it indicates
66 //! that we are done with the given value and it should be destroyed.
68 //! ## 3. Get it from C.
71 //! extern crate libc;
77 //! let my_num: *mut int = libc::malloc(mem::size_of::<int>() as libc::size_t) as *mut int;
78 //! if my_num.is_null() {
79 //! fail!("failed to allocate memory");
81 //! libc::free(my_num as *mut libc::c_void);
86 //! Usually you wouldn't literally use `malloc` and `free` from Rust,
87 //! but C APIs hand out a lot of pointers generally, so are a common source
88 //! of unsafe pointers in Rust.
93 use iter::{range, Iterator};
94 use option::{Some, None, Option};
96 #[cfg(not(test))] use cmp::{PartialEq, Eq, PartialOrd, Equiv};
98 /// Create a null pointer.
105 /// let p: *const int = ptr::null();
106 /// assert!(p.is_null());
109 #[unstable = "may need a different name after pending changes to pointer types"]
110 pub fn null<T>() -> *const T { 0 as *const T }
112 /// Create an unsafe mutable null pointer.
119 /// let p: *mut int = ptr::mut_null();
120 /// assert!(p.is_null());
123 #[unstable = "may need a different name after pending changes to pointer types"]
124 pub fn mut_null<T>() -> *mut T { 0 as *mut T }
126 /// Copies data from one location to another.
128 /// Copies `count` elements (not bytes) from `src` to `dst`. The source
129 /// and destination may overlap.
131 /// `copy_memory` is semantically equivalent to C's `memmove`.
135 /// Efficiently create a Rust vector from an unsafe buffer:
140 /// unsafe fn from_buf_raw<T>(ptr: *const T, elts: uint) -> Vec<T> {
141 /// let mut dst = Vec::with_capacity(elts);
142 /// dst.set_len(elts);
143 /// ptr::copy_memory(dst.as_mut_ptr(), ptr, elts);
150 pub unsafe fn copy_memory<T>(dst: *mut T, src: *const T, count: uint) {
151 intrinsics::copy_memory(dst, src, count)
154 /// Copies data from one location to another.
156 /// Copies `count` elements (not bytes) from `src` to `dst`. The source
157 /// and destination may *not* overlap.
159 /// `copy_nonoverlapping_memory` is semantically equivalent to C's `memcpy`.
163 /// A safe swap function:
169 /// fn swap<T>(x: &mut T, y: &mut T) {
171 /// // Give ourselves some scratch space to work with
172 /// let mut t: T = mem::uninitialized();
174 /// // Perform the swap, `&mut` pointers never alias
175 /// ptr::copy_nonoverlapping_memory(&mut t, &*x, 1);
176 /// ptr::copy_nonoverlapping_memory(x, &*y, 1);
177 /// ptr::copy_nonoverlapping_memory(y, &t, 1);
179 /// // y and t now point to the same thing, but we need to completely forget `tmp`
180 /// // because it's no longer relevant.
188 /// If the source and destination overlap then the behavior of this
189 /// function is undefined.
192 pub unsafe fn copy_nonoverlapping_memory<T>(dst: *mut T,
195 intrinsics::copy_nonoverlapping_memory(dst, src, count)
198 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
199 /// bytes of memory starting at `dst` to `c`.
201 #[experimental = "uncertain about naming and semantics"]
202 pub unsafe fn set_memory<T>(dst: *mut T, c: u8, count: uint) {
203 intrinsics::set_memory(dst, c, count)
206 /// Zeroes out `count * size_of::<T>` bytes of memory at `dst`
208 #[experimental = "uncertain about naming and semantics"]
209 #[allow(experimental)]
210 pub unsafe fn zero_memory<T>(dst: *mut T, count: uint) {
211 set_memory(dst, 0, count);
214 /// Swap the values at two mutable locations of the same type, without
215 /// deinitialising either. They may overlap.
218 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
219 // Give ourselves some scratch space to work with
220 let mut tmp: T = mem::uninitialized();
221 let t: *mut T = &mut tmp;
224 copy_nonoverlapping_memory(t, &*x, 1);
225 copy_memory(x, &*y, 1); // `x` and `y` may overlap
226 copy_nonoverlapping_memory(y, &*t, 1);
228 // y and t now point to the same thing, but we need to completely forget `tmp`
229 // because it's no longer relevant.
233 /// Replace the value at a mutable location with a new one, returning the old
234 /// value, without deinitialising either.
237 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
238 mem::swap(mem::transmute(dest), &mut src); // cannot overlap
242 /// Reads the value from `*src` and returns it.
245 pub unsafe fn read<T>(src: *const T) -> T {
246 let mut tmp: T = mem::uninitialized();
247 copy_nonoverlapping_memory(&mut tmp, src, 1);
251 /// Reads the value from `*src` and nulls it out.
252 /// This currently prevents destructors from executing.
255 #[allow(experimental)]
256 pub unsafe fn read_and_zero<T>(dest: *mut T) -> T {
257 // Copy the data out from `dest`:
258 let tmp = read(&*dest);
260 // Now zero out `dest`:
261 zero_memory(dest, 1);
266 /// Unsafely overwrite a memory location with the given value without destroying
269 /// This operation is unsafe because it does not destroy the previous value
270 /// contained at the location `dst`. This could leak allocations or resources,
271 /// so care must be taken to previously deallocate the value at `dst`.
274 pub unsafe fn write<T>(dst: *mut T, src: T) {
275 intrinsics::move_val_init(&mut *dst, src)
278 /// Given a *const *const T (pointer to an array of pointers),
279 /// iterate through each *const T, up to the provided `len`,
280 /// passing to the provided callback function
281 #[deprecated = "old-style iteration. use a loop and RawPtr::offset"]
282 pub unsafe fn array_each_with_len<T>(arr: *const *const T, len: uint,
285 fail!("ptr::array_each_with_len failure: arr input is null pointer");
287 //let start_ptr = *arr;
288 for e in range(0, len) {
289 let n = arr.offset(e as int);
294 /// Given a null-pointer-terminated *const *const T (pointer to
295 /// an array of pointers), iterate through each *const T,
296 /// passing to the provided callback function
300 /// This will only work with a null-terminated
302 #[deprecated = "old-style iteration. use a loop and RawPtr::offset"]
304 pub unsafe fn array_each<T>(arr: *const *const T, cb: |*const T|) {
306 fail!("ptr::array_each_with_len failure: arr input is null pointer");
308 let len = buf_len(arr);
309 array_each_with_len(arr, len, cb);
312 /// Return the offset of the first null pointer in `buf`.
314 #[deprecated = "use a loop and RawPtr::offset"]
316 pub unsafe fn buf_len<T>(buf: *const *const T) -> uint {
317 position(buf, |i| *i == null())
320 /// Return the first offset `i` such that `f(buf[i]) == true`.
322 #[deprecated = "old-style iteration. use a loop and RawPtr::offset"]
323 pub unsafe fn position<T>(buf: *const T, f: |&T| -> bool) -> uint {
326 if f(&(*buf.offset(i as int))) { return i; }
331 /// Methods on raw pointers
332 pub trait RawPtr<T> {
333 /// Returns the null pointer.
335 /// Returns true if the pointer is equal to the null pointer.
336 fn is_null(&self) -> bool;
337 /// Returns true if the pointer is not equal to the null pointer.
338 fn is_not_null(&self) -> bool { !self.is_null() }
339 /// Returns the value of this pointer (ie, the address it points to)
340 fn to_uint(&self) -> uint;
341 /// Returns `None` if the pointer is null, or else returns the value wrapped
346 /// While this method is useful for null-safety, it is important to note
347 /// that this is still an unsafe operation because the returned value could
348 /// be pointing to invalid memory.
349 unsafe fn to_option(&self) -> Option<&T>;
350 /// Calculates the offset from a pointer. The offset *must* be in-bounds of
351 /// the object, or one-byte-past-the-end. `count` is in units of T; e.g. a
352 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
353 unsafe fn offset(self, count: int) -> Self;
356 impl<T> RawPtr<T> for *const T {
358 fn null() -> *const T { null() }
361 fn is_null(&self) -> bool { *self == RawPtr::null() }
364 fn to_uint(&self) -> uint { *self as uint }
367 unsafe fn offset(self, count: int) -> *const T {
368 intrinsics::offset(self, count)
372 unsafe fn to_option(&self) -> Option<&T> {
381 impl<T> RawPtr<T> for *mut T {
383 fn null() -> *mut T { mut_null() }
386 fn is_null(&self) -> bool { *self == RawPtr::null() }
389 fn to_uint(&self) -> uint { *self as uint }
392 unsafe fn offset(self, count: int) -> *mut T {
393 intrinsics::offset(self as *const T, count) as *mut T
397 unsafe fn to_option(&self) -> Option<&T> {
406 // Equality for pointers
408 impl<T> PartialEq for *const T {
410 fn eq(&self, other: &*const T) -> bool {
414 fn ne(&self, other: &*const T) -> bool { !self.eq(other) }
418 impl<T> Eq for *const T {}
421 impl<T> PartialEq for *mut T {
423 fn eq(&self, other: &*mut T) -> bool {
427 fn ne(&self, other: &*mut T) -> bool { !self.eq(other) }
431 impl<T> Eq for *mut T {}
433 // Equivalence for pointers
435 impl<T> Equiv<*mut T> for *const T {
436 fn equiv(&self, other: &*mut T) -> bool {
437 self.to_uint() == other.to_uint()
442 impl<T> Equiv<*const T> for *mut T {
443 fn equiv(&self, other: &*const T) -> bool {
444 self.to_uint() == other.to_uint()
448 impl<T> Clone for *const T {
450 fn clone(&self) -> *const T {
455 impl<T> Clone for *mut T {
457 fn clone(&self) -> *mut T {
462 // Equality for extern "C" fn pointers
464 mod externfnpointers {
468 impl<_R> PartialEq for extern "C" fn() -> _R {
470 fn eq(&self, other: &extern "C" fn() -> _R) -> bool {
471 let self_: *const () = unsafe { mem::transmute(*self) };
472 let other_: *const () = unsafe { mem::transmute(*other) };
476 macro_rules! fnptreq(
478 impl<_R,$($p),*> PartialEq for extern "C" fn($($p),*) -> _R {
480 fn eq(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
481 let self_: *const () = unsafe { mem::transmute(*self) };
483 let other_: *const () = unsafe { mem::transmute(*other) };
496 // Comparison for pointers
498 impl<T> PartialOrd for *const T {
500 fn lt(&self, other: &*const T) -> bool { *self < *other }
504 impl<T> PartialOrd for *mut T {
506 fn lt(&self, other: &*mut T) -> bool { *self < *other }
510 #[allow(deprecated, experimental)]
515 use realstd::c_str::ToCStr;
519 use realstd::str::Str;
520 use realstd::vec::Vec;
521 use realstd::collections::Collection;
522 use slice::{ImmutableVector, MutableVector};
531 let mut p = Pair {fst: 10, snd: 20};
532 let pptr: *mut Pair = &mut p;
533 let iptr: *mut int = mem::transmute(pptr);
534 assert_eq!(*iptr, 10);
536 assert_eq!(*iptr, 30);
537 assert_eq!(p.fst, 30);
539 *pptr = Pair {fst: 50, snd: 60};
540 assert_eq!(*iptr, 50);
541 assert_eq!(p.fst, 50);
542 assert_eq!(p.snd, 60);
544 let v0 = vec![32000u16, 32001u16, 32002u16];
545 let mut v1 = vec![0u16, 0u16, 0u16];
547 copy_memory(v1.as_mut_ptr().offset(1),
548 v0.as_ptr().offset(1), 1);
549 assert!((*v1.get(0) == 0u16 &&
550 *v1.get(1) == 32001u16 &&
551 *v1.get(2) == 0u16));
552 copy_memory(v1.as_mut_ptr(),
553 v0.as_ptr().offset(2), 1);
554 assert!((*v1.get(0) == 32002u16 &&
555 *v1.get(1) == 32001u16 &&
556 *v1.get(2) == 0u16));
557 copy_memory(v1.as_mut_ptr().offset(2),
559 assert!((*v1.get(0) == 32002u16 &&
560 *v1.get(1) == 32001u16 &&
561 *v1.get(2) == 32000u16));
569 "hello".with_c_str(|p| {
571 assert!(2u == position(p, |c| *c == 'l' as c_char));
572 assert!(4u == position(p, |c| *c == 'o' as c_char));
573 assert!(5u == position(p, |c| *c == 0 as c_char));
580 "hello".with_c_str(|p0| {
581 "there".with_c_str(|p1| {
582 "thing".with_c_str(|p2| {
583 let v = vec![p0, p1, p2, null()];
585 assert_eq!(buf_len(v.as_ptr()), 3u);
594 let p: *const int = null();
595 assert!(p.is_null());
596 assert!(!p.is_not_null());
598 let q = unsafe { p.offset(1) };
599 assert!(!q.is_null());
600 assert!(q.is_not_null());
602 let mp: *mut int = mut_null();
603 assert!(mp.is_null());
604 assert!(!mp.is_not_null());
606 let mq = unsafe { mp.offset(1) };
607 assert!(!mq.is_null());
608 assert!(mq.is_not_null());
612 fn test_to_option() {
614 let p: *const int = null();
615 assert_eq!(p.to_option(), None);
617 let q: *const int = &2;
618 assert_eq!(q.to_option().unwrap(), &2);
620 let p: *mut int = mut_null();
621 assert_eq!(p.to_option(), None);
623 let q: *mut int = &mut 2;
624 assert_eq!(q.to_option().unwrap(), &2);
629 fn test_ptr_addition() {
631 let xs = Vec::from_elem(16, 5i);
632 let mut ptr = xs.as_ptr();
633 let end = ptr.offset(16);
641 let mut m_ptr = xs_mut.as_mut_ptr();
642 let m_end = m_ptr.offset(16);
644 while m_ptr < m_end {
646 m_ptr = m_ptr.offset(1);
649 assert!(xs_mut == Vec::from_elem(16, 10i));
654 fn test_ptr_subtraction() {
656 let xs = vec![0,1,2,3,4,5,6,7,8,9];
658 let ptr = xs.as_ptr();
661 assert_eq!(*(ptr.offset(idx as int)), idx as int);
666 let m_start = xs_mut.as_mut_ptr();
667 let mut m_ptr = m_start.offset(9);
669 while m_ptr >= m_start {
671 m_ptr = m_ptr.offset(-1);
674 assert!(xs_mut == vec![0,2,4,6,8,10,12,14,16,18]);
679 fn test_ptr_array_each_with_len() {
681 let one = "oneOne".to_c_str();
682 let two = "twoTwo".to_c_str();
683 let three = "threeThree".to_c_str();
685 one.with_ref(|buf| buf),
686 two.with_ref(|buf| buf),
687 three.with_ref(|buf| buf)
694 let mut iteration_count = 0;
695 array_each_with_len(arr.as_ptr(), arr.len(), |e| {
696 let actual = str::raw::from_c_str(e);
697 let expected = expected_arr[ctr].with_ref(|buf| {
698 str::raw::from_c_str(buf)
700 assert_eq!(actual.as_slice(), expected.as_slice());
702 iteration_count += 1;
704 assert_eq!(iteration_count, 3u);
709 fn test_ptr_array_each() {
711 let one = "oneOne".to_c_str();
712 let two = "twoTwo".to_c_str();
713 let three = "threeThree".to_c_str();
715 one.with_ref(|buf| buf),
716 two.with_ref(|buf| buf),
717 three.with_ref(|buf| buf),
718 // fake a null terminator
725 let arr_ptr = arr.as_ptr();
727 let mut iteration_count = 0u;
728 array_each(arr_ptr, |e| {
729 let actual = str::raw::from_c_str(e);
730 let expected = expected_arr[ctr].with_ref(|buf| {
731 str::raw::from_c_str(buf)
733 assert_eq!(actual.as_slice(), expected.as_slice());
735 iteration_count += 1;
737 assert_eq!(iteration_count, 3);
743 fn test_ptr_array_each_with_len_null_ptr() {
745 array_each_with_len(0 as *const *const libc::c_char, 1, |e| {
746 str::raw::from_c_str(e);
752 fn test_ptr_array_each_null_ptr() {
754 array_each(0 as *const *const libc::c_char, |e| {
755 str::raw::from_c_str(e);
761 fn test_set_memory() {
762 let mut xs = [0u8, ..20];
763 let ptr = xs.as_mut_ptr();
764 unsafe { set_memory(ptr, 5u8, xs.len()); }
765 assert!(xs == [5u8, ..20]);