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;
23 #[cfg(not(test))] use cmp::{Eq, Ord};
25 /// Calculate the offset from a pointer.
26 /// The `count` argument is in units of T; e.g. a `count` of 3
27 /// represents a pointer offset of `3 * sizeof::<T>()` bytes.
29 pub unsafe fn offset<T>(ptr: *T, count: int) -> *T {
30 intrinsics::offset(ptr, count)
33 /// Calculate the offset from a mut pointer. The count *must* be in bounds or
34 /// otherwise the loads of this address are undefined.
35 /// The `count` argument is in units of T; e.g. a `count` of 3
36 /// represents a pointer offset of `3 * sizeof::<T>()` bytes.
38 pub unsafe fn mut_offset<T>(ptr: *mut T, count: int) -> *mut T {
39 intrinsics::offset(ptr as *T, count) as *mut T
42 /// Return the offset of the first null pointer in `buf`.
44 pub unsafe fn buf_len<T>(buf: **T) -> uint {
45 position(buf, |i| *i == null())
48 impl<T> Clone for *T {
50 fn clone(&self) -> *T {
55 impl<T> Clone for *mut T {
57 fn clone(&self) -> *mut T {
62 /// Return the first offset `i` such that `f(buf[i]) == true`.
64 pub unsafe fn position<T>(buf: *T, f: |&T| -> bool) -> uint {
67 if f(&(*offset(buf, i as int))) { return i; }
72 /// Create an unsafe null pointer
74 pub fn null<T>() -> *T { 0 as *T }
76 /// Create an unsafe mutable null pointer
78 pub fn mut_null<T>() -> *mut T { 0 as *mut T }
80 /// Returns true if the pointer is equal to the null pointer.
82 pub fn is_null<T,P:RawPtr<T>>(ptr: P) -> bool { ptr.is_null() }
84 /// Returns true if the pointer is not equal to the null pointer.
86 pub fn is_not_null<T,P:RawPtr<T>>(ptr: P) -> bool { ptr.is_not_null() }
89 * Copies data from one location to another.
91 * Copies `count` elements (not bytes) from `src` to `dst`. The source
92 * and destination may overlap.
95 pub unsafe fn copy_memory<T,P:RawPtr<T>>(dst: *mut T, src: P, count: uint) {
96 intrinsics::copy_memory(dst, cast::transmute_immut_unsafe(src), count)
100 * Copies data from one location to another.
102 * Copies `count` elements (not bytes) from `src` to `dst`. The source
103 * and destination may *not* overlap.
106 pub unsafe fn copy_nonoverlapping_memory<T,P:RawPtr<T>>(dst: *mut T,
109 intrinsics::copy_nonoverlapping_memory(dst, cast::transmute_immut_unsafe(src), count)
113 * Invokes memset on the specified pointer, setting `count * size_of::<T>()`
114 * bytes of memory starting at `dst` to `c`.
117 pub unsafe fn set_memory<T>(dst: *mut T, c: u8, count: uint) {
118 intrinsics::set_memory(dst, c, count)
122 * Zeroes out `count * size_of::<T>` bytes of memory at `dst`
125 pub unsafe fn zero_memory<T>(dst: *mut T, count: uint) {
126 set_memory(dst, 0, count);
130 * Swap the values at two mutable locations of the same type, without
131 * deinitialising or copying either one.
134 pub unsafe fn swap_ptr<T>(x: *mut T, y: *mut T) {
135 // Give ourselves some scratch space to work with
136 let mut tmp: T = mem::uninit();
137 let t: *mut T = &mut tmp;
140 copy_nonoverlapping_memory(t, x, 1);
141 copy_memory(x, y, 1); // `x` and `y` may overlap
142 copy_nonoverlapping_memory(y, t, 1);
144 // y and t now point to the same thing, but we need to completely forget `tmp`
145 // because it's no longer relevant.
150 * Replace the value at a mutable location with a new one, returning the old
151 * value, without deinitialising or copying either one.
154 pub unsafe fn replace_ptr<T>(dest: *mut T, mut src: T) -> T {
155 swap(cast::transmute(dest), &mut src); // cannot overlap
160 * Reads the value from `*src` and returns it. Does not copy `*src`.
163 pub unsafe fn read_ptr<T>(src: *T) -> T {
164 let mut tmp: T = mem::uninit();
165 copy_nonoverlapping_memory(&mut tmp, src, 1);
170 * Reads the value from `*src` and nulls it out.
171 * This currently prevents destructors from executing.
174 pub unsafe fn read_and_zero_ptr<T>(dest: *mut T) -> T {
175 // Copy the data out from `dest`:
176 let tmp = read_ptr(&*dest);
178 // Now zero out `dest`:
179 zero_memory(dest, 1);
184 /// Transform a region pointer - &T - to an unsafe pointer - *T.
186 pub fn to_unsafe_ptr<T>(thing: &T) -> *T {
190 /// Transform a mutable region pointer - &mut T - to a mutable unsafe pointer - *mut T.
192 pub fn to_mut_unsafe_ptr<T>(thing: &mut T) -> *mut T {
197 Given a **T (pointer to an array of pointers),
198 iterate through each *T, up to the provided `len`,
199 passing to the provided callback function
201 SAFETY NOTE: Pointer-arithmetic. Dragons be here.
203 pub unsafe fn array_each_with_len<T>(arr: **T, len: uint, cb: |*T|) {
204 debug!("array_each_with_len: before iterate");
205 if arr as uint == 0 {
206 fail!("ptr::array_each_with_len failure: arr input is null pointer");
208 //let start_ptr = *arr;
209 for e in range(0, len) {
210 let n = offset(arr, e as int);
213 debug!("array_each_with_len: after iterate");
217 Given a null-pointer-terminated **T (pointer to
218 an array of pointers), iterate through each *T,
219 passing to the provided callback function
221 SAFETY NOTE: This will only work with a null-terminated
222 pointer array. Barely less-dodgy Pointer Arithmetic.
225 pub unsafe fn array_each<T>(arr: **T, cb: |*T|) {
226 if arr as uint == 0 {
227 fail!("ptr::array_each_with_len failure: arr input is null pointer");
229 let len = buf_len(arr);
230 debug!("array_each inferred len: {}", len);
231 array_each_with_len(arr, len, cb);
234 #[allow(missing_doc)]
235 pub trait RawPtr<T> {
237 fn is_null(&self) -> bool;
238 fn is_not_null(&self) -> bool;
239 fn to_uint(&self) -> uint;
240 unsafe fn to_option(&self) -> Option<&T>;
241 unsafe fn offset(self, count: int) -> Self;
244 /// Extension methods for immutable pointers
245 impl<T> RawPtr<T> for *T {
246 /// Returns the null pointer.
248 fn null() -> *T { null() }
250 /// Returns true if the pointer is equal to the null pointer.
252 fn is_null(&self) -> bool { *self == RawPtr::null() }
254 /// Returns true if the pointer is not equal to the null pointer.
256 fn is_not_null(&self) -> bool { *self != RawPtr::null() }
258 /// Returns the address of this pointer.
260 fn to_uint(&self) -> uint { *self as uint }
263 /// Returns `None` if the pointer is null, or else returns the value wrapped
268 /// While this method is useful for null-safety, it is important to note
269 /// that this is still an unsafe operation because the returned value could
270 /// be pointing to invalid memory.
273 unsafe fn to_option(&self) -> Option<&T> {
274 if self.is_null() { None } else {
275 Some(cast::transmute(*self))
279 /// Calculates the offset from a pointer. The offset *must* be in-bounds of
280 /// the object, or one-byte-past-the-end.
282 unsafe fn offset(self, count: int) -> *T { offset(self, count) }
285 /// Extension methods for mutable pointers
286 impl<T> RawPtr<T> for *mut T {
287 /// Returns the null pointer.
289 fn null() -> *mut T { mut_null() }
291 /// Returns true if the pointer is equal to the null pointer.
293 fn is_null(&self) -> bool { *self == RawPtr::null() }
295 /// Returns true if the pointer is not equal to the null pointer.
297 fn is_not_null(&self) -> bool { *self != RawPtr::null() }
299 /// Returns the address of this pointer.
301 fn to_uint(&self) -> uint { *self as uint }
304 /// Returns `None` if the pointer is null, or else returns the value wrapped
309 /// While this method is useful for null-safety, it is important to note
310 /// that this is still an unsafe operation because the returned value could
311 /// be pointing to invalid memory.
314 unsafe fn to_option(&self) -> Option<&T> {
315 if self.is_null() { None } else {
316 Some(cast::transmute(*self))
320 /// Calculates the offset from a pointer. The offset *must* be in-bounds of
321 /// the object, or one-byte-past-the-end. An arithmetic overflow is also
322 /// undefined behaviour.
324 /// This method should be preferred over `offset` when the guarantee can be
325 /// satisfied, to enable better optimization.
327 unsafe fn offset(self, count: int) -> *mut T { mut_offset(self, count) }
330 // Equality for pointers
334 fn eq(&self, other: &*T) -> bool {
338 fn ne(&self, other: &*T) -> bool { !self.eq(other) }
342 impl<T> Eq for *mut T {
344 fn eq(&self, other: &*mut T) -> bool {
348 fn ne(&self, other: &*mut T) -> bool { !self.eq(other) }
351 // Equivalence for pointers
353 impl<T> Equiv<*mut T> for *T {
354 fn equiv(&self, other: &*mut T) -> bool {
355 self.to_uint() == other.to_uint()
360 impl<T> Equiv<*T> for *mut T {
361 fn equiv(&self, other: &*T) -> bool {
362 self.to_uint() == other.to_uint()
366 // Equality for extern "C" fn pointers
368 mod externfnpointers {
372 impl<_R> Eq for extern "C" fn() -> _R {
374 fn eq(&self, other: &extern "C" fn() -> _R) -> bool {
375 let self_: *() = unsafe { cast::transmute(*self) };
376 let other_: *() = unsafe { cast::transmute(*other) };
380 fn ne(&self, other: &extern "C" fn() -> _R) -> bool {
384 macro_rules! fnptreq(
386 impl<_R,$($p),*> Eq for extern "C" fn($($p),*) -> _R {
388 fn eq(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
389 let self_: *() = unsafe { cast::transmute(*self) };
390 let other_: *() = unsafe { cast::transmute(*other) };
394 fn ne(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
407 // Comparison for pointers
411 fn lt(&self, other: &*T) -> bool {
415 fn le(&self, other: &*T) -> bool {
419 fn ge(&self, other: &*T) -> bool {
423 fn gt(&self, other: &*T) -> bool {
429 impl<T> Ord for *mut T {
431 fn lt(&self, other: &*mut T) -> bool {
435 fn le(&self, other: &*mut T) -> bool {
439 fn ge(&self, other: &*mut T) -> bool {
443 fn gt(&self, other: &*mut T) -> bool {
457 use vec::{ImmutableVector, MutableVector};
466 let mut p = Pair {fst: 10, snd: 20};
467 let pptr: *mut Pair = &mut p;
468 let iptr: *mut int = cast::transmute(pptr);
469 assert_eq!(*iptr, 10);
471 assert_eq!(*iptr, 30);
472 assert_eq!(p.fst, 30);
474 *pptr = Pair {fst: 50, snd: 60};
475 assert_eq!(*iptr, 50);
476 assert_eq!(p.fst, 50);
477 assert_eq!(p.snd, 60);
479 let v0 = ~[32000u16, 32001u16, 32002u16];
480 let mut v1 = ~[0u16, 0u16, 0u16];
482 copy_memory(mut_offset(v1.as_mut_ptr(), 1),
483 offset(v0.as_ptr(), 1), 1);
484 assert!((v1[0] == 0u16 && v1[1] == 32001u16 && v1[2] == 0u16));
485 copy_memory(v1.as_mut_ptr(),
486 offset(v0.as_ptr(), 2), 1);
487 assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
489 copy_memory(mut_offset(v1.as_mut_ptr(), 2),
491 assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
500 "hello".with_c_str(|p| {
502 assert!(2u == position(p, |c| *c == 'l' as c_char));
503 assert!(4u == position(p, |c| *c == 'o' as c_char));
504 assert!(5u == position(p, |c| *c == 0 as c_char));
511 "hello".with_c_str(|p0| {
512 "there".with_c_str(|p1| {
513 "thing".with_c_str(|p2| {
514 let v = ~[p0, p1, p2, null()];
516 assert_eq!(buf_len(v.as_ptr()), 3u);
525 let p: *int = null();
526 assert!(p.is_null());
527 assert!(!p.is_not_null());
529 let q = unsafe { offset(p, 1) };
530 assert!(!q.is_null());
531 assert!(q.is_not_null());
533 let mp: *mut int = mut_null();
534 assert!(mp.is_null());
535 assert!(!mp.is_not_null());
537 let mq = unsafe { mp.offset(1) };
538 assert!(!mq.is_null());
539 assert!(mq.is_not_null());
543 fn test_to_option() {
545 let p: *int = null();
546 assert_eq!(p.to_option(), None);
549 assert_eq!(q.to_option().unwrap(), &2);
551 let p: *mut int = mut_null();
552 assert_eq!(p.to_option(), None);
554 let q: *mut int = &mut 2;
555 assert_eq!(q.to_option().unwrap(), &2);
560 fn test_ptr_addition() {
563 let mut ptr = xs.as_ptr();
564 let end = ptr.offset(16);
571 let mut xs_mut = xs.clone();
572 let mut m_ptr = xs_mut.as_mut_ptr();
573 let m_end = m_ptr.offset(16);
575 while m_ptr < m_end {
577 m_ptr = m_ptr.offset(1);
580 assert_eq!(xs_mut, ~[10, ..16]);
585 fn test_ptr_subtraction() {
587 let xs = ~[0,1,2,3,4,5,6,7,8,9];
589 let ptr = xs.as_ptr();
592 assert_eq!(*(ptr.offset(idx as int)), idx as int);
596 let mut xs_mut = xs.clone();
597 let m_start = xs_mut.as_mut_ptr();
598 let mut m_ptr = m_start.offset(9);
600 while m_ptr >= m_start {
602 m_ptr = m_ptr.offset(-1);
605 assert_eq!(xs_mut, ~[0,2,4,6,8,10,12,14,16,18]);
610 fn test_ptr_array_each_with_len() {
612 let one = "oneOne".to_c_str();
613 let two = "twoTwo".to_c_str();
614 let three = "threeThree".to_c_str();
616 one.with_ref(|buf| buf),
617 two.with_ref(|buf| buf),
618 three.with_ref(|buf| buf),
625 let mut iteration_count = 0;
626 array_each_with_len(arr.as_ptr(), arr.len(), |e| {
627 let actual = str::raw::from_c_str(e);
628 let expected = expected_arr[ctr].with_ref(|buf| {
629 str::raw::from_c_str(buf)
632 "test_ptr_array_each_with_len e: {}, a: {}",
634 assert_eq!(actual, expected);
636 iteration_count += 1;
638 assert_eq!(iteration_count, 3u);
643 fn test_ptr_array_each() {
645 let one = "oneOne".to_c_str();
646 let two = "twoTwo".to_c_str();
647 let three = "threeThree".to_c_str();
649 one.with_ref(|buf| buf),
650 two.with_ref(|buf| buf),
651 three.with_ref(|buf| buf),
652 // fake a null terminator
659 let arr_ptr = arr.as_ptr();
661 let mut iteration_count = 0;
662 array_each(arr_ptr, |e| {
663 let actual = str::raw::from_c_str(e);
664 let expected = expected_arr[ctr].with_ref(|buf| {
665 str::raw::from_c_str(buf)
668 "test_ptr_array_each e: {}, a: {}",
670 assert_eq!(actual, expected);
672 iteration_count += 1;
674 assert_eq!(iteration_count, 3);
680 fn test_ptr_array_each_with_len_null_ptr() {
682 array_each_with_len(0 as **libc::c_char, 1, |e| {
683 str::raw::from_c_str(e);
689 fn test_ptr_array_each_null_ptr() {
691 array_each(0 as **libc::c_char, |e| {
692 str::raw::from_c_str(e);
698 fn test_set_memory() {
699 let mut xs = [0u8, ..20];
700 let ptr = xs.as_mut_ptr();
701 unsafe { set_memory(ptr, 5u8, xs.len()); }
702 assert_eq!(xs, [5u8, ..20]);