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 //! Unsafe pointer utility functions
17 use iter::{range, Iterator};
19 use option::{Option, Some, None};
20 use unstable::intrinsics;
22 #[cfg(not(test))] use cmp::{Eq, Ord};
24 /// Return the offset of the first null pointer in `buf`.
26 pub unsafe fn buf_len<T>(buf: **T) -> uint {
27 position(buf, |i| *i == null())
30 impl<T> Clone for *T {
32 fn clone(&self) -> *T {
37 impl<T> Clone for *mut T {
39 fn clone(&self) -> *mut T {
44 /// Return the first offset `i` such that `f(buf[i]) == true`.
46 pub unsafe fn position<T>(buf: *T, f: |&T| -> bool) -> uint {
49 if f(&(*buf.offset(i as int))) { return i; }
54 /// Create an unsafe null pointer
56 pub fn null<T>() -> *T { 0 as *T }
58 /// Create an unsafe mutable null pointer
60 pub fn mut_null<T>() -> *mut T { 0 as *mut T }
63 * Copies data from one location to another.
65 * Copies `count` elements (not bytes) from `src` to `dst`. The source
66 * and destination may overlap.
69 pub unsafe fn copy_memory<T>(dst: *mut T, src: *T, count: uint) {
70 intrinsics::copy_memory(dst, src, count)
74 * Copies data from one location to another.
76 * Copies `count` elements (not bytes) from `src` to `dst`. The source
77 * and destination may *not* overlap.
80 pub unsafe fn copy_nonoverlapping_memory<T>(dst: *mut T,
83 intrinsics::copy_nonoverlapping_memory(dst, src, count)
87 * Invokes memset on the specified pointer, setting `count * size_of::<T>()`
88 * bytes of memory starting at `dst` to `c`.
91 pub unsafe fn set_memory<T>(dst: *mut T, c: u8, count: uint) {
92 intrinsics::set_memory(dst, c, count)
96 * Zeroes out `count * size_of::<T>` bytes of memory at `dst`
99 pub unsafe fn zero_memory<T>(dst: *mut T, count: uint) {
100 set_memory(dst, 0, count);
104 * Swap the values at two mutable locations of the same type, without
105 * deinitialising either. They may overlap.
108 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
109 // Give ourselves some scratch space to work with
110 let mut tmp: T = mem::uninit();
111 let t: *mut T = &mut tmp;
114 copy_nonoverlapping_memory(t, &*x, 1);
115 copy_memory(x, &*y, 1); // `x` and `y` may overlap
116 copy_nonoverlapping_memory(y, &*t, 1);
118 // y and t now point to the same thing, but we need to completely forget `tmp`
119 // because it's no longer relevant.
124 * Replace the value at a mutable location with a new one, returning the old
125 * value, without deinitialising either.
128 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
129 mem::swap(cast::transmute(dest), &mut src); // cannot overlap
134 * Reads the value from `*src` and returns it.
137 pub unsafe fn read<T>(src: *T) -> T {
138 let mut tmp: T = mem::uninit();
139 copy_nonoverlapping_memory(&mut tmp, src, 1);
144 * Reads the value from `*src` and nulls it out.
145 * This currently prevents destructors from executing.
148 pub unsafe fn read_and_zero<T>(dest: *mut T) -> T {
149 // Copy the data out from `dest`:
150 let tmp = read(&*dest);
152 // Now zero out `dest`:
153 zero_memory(dest, 1);
159 Given a **T (pointer to an array of pointers),
160 iterate through each *T, up to the provided `len`,
161 passing to the provided callback function
163 SAFETY NOTE: Pointer-arithmetic. Dragons be here.
165 pub unsafe fn array_each_with_len<T>(arr: **T, len: uint, cb: |*T|) {
166 debug!("array_each_with_len: before iterate");
168 fail!("ptr::array_each_with_len failure: arr input is null pointer");
170 //let start_ptr = *arr;
171 for e in range(0, len) {
172 let n = arr.offset(e as int);
175 debug!("array_each_with_len: after iterate");
179 Given a null-pointer-terminated **T (pointer to
180 an array of pointers), iterate through each *T,
181 passing to the provided callback function
183 SAFETY NOTE: This will only work with a null-terminated
184 pointer array. Barely less-dodgy Pointer Arithmetic.
187 pub unsafe fn array_each<T>(arr: **T, cb: |*T|) {
189 fail!("ptr::array_each_with_len failure: arr input is null pointer");
191 let len = buf_len(arr);
192 debug!("array_each inferred len: {}", len);
193 array_each_with_len(arr, len, cb);
196 /// Extension methods for raw pointers.
197 pub trait RawPtr<T> {
198 /// Returns the null pointer.
200 /// Returns true if the pointer is equal to the null pointer.
201 fn is_null(&self) -> bool;
202 /// Returns true if the pointer is not equal to the null pointer.
203 fn is_not_null(&self) -> bool { !self.is_null() }
204 /// Returns the value of this pointer (ie, the address it points to)
205 fn to_uint(&self) -> uint;
206 /// Returns `None` if the pointer is null, or else returns the value wrapped
211 /// While this method is useful for null-safety, it is important to note
212 /// that this is still an unsafe operation because the returned value could
213 /// be pointing to invalid memory.
214 unsafe fn to_option(&self) -> Option<&T>;
215 /// Calculates the offset from a pointer. The offset *must* be in-bounds of
216 /// the object, or one-byte-past-the-end.
217 unsafe fn offset(self, count: int) -> Self;
220 impl<T> RawPtr<T> for *T {
222 fn null() -> *T { null() }
225 fn is_null(&self) -> bool { *self == RawPtr::null() }
228 fn to_uint(&self) -> uint { *self as uint }
231 unsafe fn offset(self, count: int) -> *T { intrinsics::offset(self, count) }
234 unsafe fn to_option(&self) -> Option<&T> {
238 Some(cast::transmute(*self))
243 impl<T> RawPtr<T> for *mut T {
245 fn null() -> *mut T { mut_null() }
248 fn is_null(&self) -> bool { *self == RawPtr::null() }
251 fn to_uint(&self) -> uint { *self as uint }
254 unsafe fn offset(self, count: int) -> *mut T { intrinsics::offset(self as *T, count) as *mut T }
257 unsafe fn to_option(&self) -> Option<&T> {
261 Some(cast::transmute(*self))
266 // Equality for pointers
270 fn eq(&self, other: &*T) -> bool {
274 fn ne(&self, other: &*T) -> bool { !self.eq(other) }
278 impl<T> Eq for *mut T {
280 fn eq(&self, other: &*mut T) -> bool {
284 fn ne(&self, other: &*mut T) -> bool { !self.eq(other) }
287 // Equivalence for pointers
289 impl<T> Equiv<*mut T> for *T {
290 fn equiv(&self, other: &*mut T) -> bool {
291 self.to_uint() == other.to_uint()
296 impl<T> Equiv<*T> for *mut T {
297 fn equiv(&self, other: &*T) -> bool {
298 self.to_uint() == other.to_uint()
302 // Equality for extern "C" fn pointers
304 mod externfnpointers {
308 impl<_R> Eq for extern "C" fn() -> _R {
310 fn eq(&self, other: &extern "C" fn() -> _R) -> bool {
311 let self_: *() = unsafe { cast::transmute(*self) };
312 let other_: *() = unsafe { cast::transmute(*other) };
316 fn ne(&self, other: &extern "C" fn() -> _R) -> bool {
320 macro_rules! fnptreq(
322 impl<_R,$($p),*> Eq for extern "C" fn($($p),*) -> _R {
324 fn eq(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
325 let self_: *() = unsafe { cast::transmute(*self) };
326 let other_: *() = unsafe { cast::transmute(*other) };
330 fn ne(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
343 // Comparison for pointers
347 fn lt(&self, other: &*T) -> bool {
351 fn le(&self, other: &*T) -> bool {
355 fn ge(&self, other: &*T) -> bool {
359 fn gt(&self, other: &*T) -> bool {
365 impl<T> Ord for *mut T {
367 fn lt(&self, other: &*mut T) -> bool {
371 fn le(&self, other: &*mut T) -> bool {
375 fn ge(&self, other: &*mut T) -> bool {
379 fn gt(&self, other: &*mut T) -> bool {
393 use vec::{ImmutableVector, MutableVector};
402 let mut p = Pair {fst: 10, snd: 20};
403 let pptr: *mut Pair = &mut p;
404 let iptr: *mut int = cast::transmute(pptr);
405 assert_eq!(*iptr, 10);
407 assert_eq!(*iptr, 30);
408 assert_eq!(p.fst, 30);
410 *pptr = Pair {fst: 50, snd: 60};
411 assert_eq!(*iptr, 50);
412 assert_eq!(p.fst, 50);
413 assert_eq!(p.snd, 60);
415 let v0 = ~[32000u16, 32001u16, 32002u16];
416 let mut v1 = ~[0u16, 0u16, 0u16];
418 copy_memory(v1.as_mut_ptr().offset(1),
419 v0.as_ptr().offset(1), 1);
420 assert!((v1[0] == 0u16 && v1[1] == 32001u16 && v1[2] == 0u16));
421 copy_memory(v1.as_mut_ptr(),
422 v0.as_ptr().offset(2), 1);
423 assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
425 copy_memory(v1.as_mut_ptr().offset(2),
427 assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
436 "hello".with_c_str(|p| {
438 assert!(2u == position(p, |c| *c == 'l' as c_char));
439 assert!(4u == position(p, |c| *c == 'o' as c_char));
440 assert!(5u == position(p, |c| *c == 0 as c_char));
447 "hello".with_c_str(|p0| {
448 "there".with_c_str(|p1| {
449 "thing".with_c_str(|p2| {
450 let v = ~[p0, p1, p2, null()];
452 assert_eq!(buf_len(v.as_ptr()), 3u);
461 let p: *int = null();
462 assert!(p.is_null());
463 assert!(!p.is_not_null());
465 let q = unsafe { p.offset(1) };
466 assert!(!q.is_null());
467 assert!(q.is_not_null());
469 let mp: *mut int = mut_null();
470 assert!(mp.is_null());
471 assert!(!mp.is_not_null());
473 let mq = unsafe { mp.offset(1) };
474 assert!(!mq.is_null());
475 assert!(mq.is_not_null());
479 fn test_to_option() {
481 let p: *int = null();
482 assert_eq!(p.to_option(), None);
485 assert_eq!(q.to_option().unwrap(), &2);
487 let p: *mut int = mut_null();
488 assert_eq!(p.to_option(), None);
490 let q: *mut int = &mut 2;
491 assert_eq!(q.to_option().unwrap(), &2);
496 fn test_ptr_addition() {
499 let mut ptr = xs.as_ptr();
500 let end = ptr.offset(16);
507 let mut xs_mut = xs.clone();
508 let mut m_ptr = xs_mut.as_mut_ptr();
509 let m_end = m_ptr.offset(16);
511 while m_ptr < m_end {
513 m_ptr = m_ptr.offset(1);
516 assert_eq!(xs_mut, ~[10, ..16]);
521 fn test_ptr_subtraction() {
523 let xs = ~[0,1,2,3,4,5,6,7,8,9];
525 let ptr = xs.as_ptr();
528 assert_eq!(*(ptr.offset(idx as int)), idx as int);
532 let mut xs_mut = xs.clone();
533 let m_start = xs_mut.as_mut_ptr();
534 let mut m_ptr = m_start.offset(9);
536 while m_ptr >= m_start {
538 m_ptr = m_ptr.offset(-1);
541 assert_eq!(xs_mut, ~[0,2,4,6,8,10,12,14,16,18]);
546 fn test_ptr_array_each_with_len() {
548 let one = "oneOne".to_c_str();
549 let two = "twoTwo".to_c_str();
550 let three = "threeThree".to_c_str();
552 one.with_ref(|buf| buf),
553 two.with_ref(|buf| buf),
554 three.with_ref(|buf| buf),
561 let mut iteration_count = 0;
562 array_each_with_len(arr.as_ptr(), arr.len(), |e| {
563 let actual = str::raw::from_c_str(e);
564 let expected = expected_arr[ctr].with_ref(|buf| {
565 str::raw::from_c_str(buf)
568 "test_ptr_array_each_with_len e: {}, a: {}",
570 assert_eq!(actual, expected);
572 iteration_count += 1;
574 assert_eq!(iteration_count, 3u);
579 fn test_ptr_array_each() {
581 let one = "oneOne".to_c_str();
582 let two = "twoTwo".to_c_str();
583 let three = "threeThree".to_c_str();
585 one.with_ref(|buf| buf),
586 two.with_ref(|buf| buf),
587 three.with_ref(|buf| buf),
588 // fake a null terminator
595 let arr_ptr = arr.as_ptr();
597 let mut iteration_count = 0;
598 array_each(arr_ptr, |e| {
599 let actual = str::raw::from_c_str(e);
600 let expected = expected_arr[ctr].with_ref(|buf| {
601 str::raw::from_c_str(buf)
604 "test_ptr_array_each e: {}, a: {}",
606 assert_eq!(actual, expected);
608 iteration_count += 1;
610 assert_eq!(iteration_count, 3);
616 fn test_ptr_array_each_with_len_null_ptr() {
618 array_each_with_len(0 as **libc::c_char, 1, |e| {
619 str::raw::from_c_str(e);
625 fn test_ptr_array_each_null_ptr() {
627 array_each(0 as **libc::c_char, |e| {
628 str::raw::from_c_str(e);
634 fn test_set_memory() {
635 let mut xs = [0u8, ..20];
636 let ptr = xs.as_mut_ptr();
637 unsafe { set_memory(ptr, 5u8, xs.len()); }
638 assert_eq!(xs, [5u8, ..20]);