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
15 use iterator::{range, Iterator};
16 use option::{Option, Some, None};
17 use unstable::intrinsics;
20 #[cfg(not(test))] use ops::{Add,Sub};
21 #[cfg(not(test))] use num::Int;
23 #[cfg(not(test))] use cmp::{Eq, Ord};
25 /// Calculate the offset from a pointer
27 pub fn offset<T>(ptr: *T, count: int) -> *T {
28 unsafe { intrinsics::offset(ptr, count) }
31 /// Calculate the offset from a const pointer
33 pub fn const_offset<T>(ptr: *const T, count: int) -> *const T {
34 unsafe { intrinsics::offset(ptr as *T, count) }
37 /// Calculate the offset from a mut pointer
39 pub fn mut_offset<T>(ptr: *mut T, count: int) -> *mut T {
40 unsafe { intrinsics::offset(ptr as *T, count) as *mut T }
43 /// Return the offset of the first null pointer in `buf`.
45 pub unsafe fn buf_len<T>(buf: **T) -> uint {
46 position(buf, |i| *i == null())
49 impl<T> Clone for *T {
50 fn clone(&self) -> *T {
55 /// Return the first offset `i` such that `f(buf[i]) == true`.
57 pub unsafe fn position<T>(buf: *T, f: &fn(&T) -> bool) -> uint {
60 if f(&(*offset(buf, i as int))) { return i; }
65 /// Create an unsafe null pointer
67 pub fn null<T>() -> *T { 0 as *T }
69 /// Create an unsafe mutable null pointer
71 pub fn mut_null<T>() -> *mut T { 0 as *mut T }
73 /// Returns true if the pointer is equal to the null pointer.
75 pub fn is_null<T>(ptr: *const T) -> bool { ptr == null() }
77 /// Returns true if the pointer is not equal to the null pointer.
79 pub fn is_not_null<T>(ptr: *const T) -> bool { !is_null(ptr) }
82 * Copies data from one location to another.
84 * Copies `count` elements (not bytes) from `src` to `dst`. The source
85 * and destination may overlap.
88 #[cfg(target_word_size = "32")]
89 pub unsafe fn copy_memory<T>(dst: *mut T, src: *const T, count: uint) {
90 intrinsics::memmove32(dst, src as *T, count as u32);
94 * Copies data from one location to another.
96 * Copies `count` elements (not bytes) from `src` to `dst`. The source
97 * and destination may overlap.
100 #[cfg(target_word_size = "64")]
101 pub unsafe fn copy_memory<T>(dst: *mut T, src: *const T, count: uint) {
102 intrinsics::memmove64(dst, src as *T, count as u64);
106 * Copies data from one location to another.
108 * Copies `count` elements (not bytes) from `src` to `dst`. The source
109 * and destination may *not* overlap.
112 #[cfg(target_word_size = "32")]
113 pub unsafe fn copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: uint) {
114 intrinsics::memcpy32(dst, src as *T, count as u32);
118 * Copies data from one location to another.
120 * Copies `count` elements (not bytes) from `src` to `dst`. The source
121 * and destination may *not* overlap.
124 #[cfg(target_word_size = "64")]
125 pub unsafe fn copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: uint) {
126 intrinsics::memcpy64(dst, src as *T, count as u64);
130 * Invokes memset on the specified pointer, setting `count * size_of::<T>()`
131 * bytes of memory starting at `dst` to `c`.
134 #[cfg(target_word_size = "32")]
135 pub unsafe fn set_memory<T>(dst: *mut T, c: u8, count: uint) {
136 intrinsics::memset32(dst, c, count as u32);
140 * Invokes memset on the specified pointer, setting `count * size_of::<T>()`
141 * bytes of memory starting at `dst` to `c`.
144 #[cfg(target_word_size = "64")]
145 pub unsafe fn set_memory<T>(dst: *mut T, c: u8, count: uint) {
146 intrinsics::memset64(dst, c, count as u64);
150 * Zeroes out `count * size_of::<T>` bytes of memory at `dst`
153 pub unsafe fn zero_memory<T>(dst: *mut T, count: uint) {
154 set_memory(dst, 0, count);
158 * Swap the values at two mutable locations of the same type, without
159 * deinitialising or copying either one.
162 pub unsafe fn swap_ptr<T>(x: *mut T, y: *mut T) {
163 // Give ourselves some scratch space to work with
164 let mut tmp: T = intrinsics::uninit();
165 let t: *mut T = &mut tmp;
168 copy_nonoverlapping_memory(t, x, 1);
169 copy_memory(x, y, 1); // `x` and `y` may overlap
170 copy_nonoverlapping_memory(y, t, 1);
172 // y and t now point to the same thing, but we need to completely forget `tmp`
173 // because it's no longer relevant.
178 * Replace the value at a mutable location with a new one, returning the old
179 * value, without deinitialising or copying either one.
182 pub unsafe fn replace_ptr<T>(dest: *mut T, mut src: T) -> T {
183 swap(cast::transmute(dest), &mut src); // cannot overlap
188 * Reads the value from `*src` and returns it. Does not copy `*src`.
191 pub unsafe fn read_ptr<T>(src: *mut T) -> T {
192 let mut tmp: T = intrinsics::uninit();
193 copy_nonoverlapping_memory(&mut tmp, src, 1);
198 * Reads the value from `*src` and nulls it out.
199 * This currently prevents destructors from executing.
202 pub unsafe fn read_and_zero_ptr<T>(dest: *mut T) -> T {
203 // Copy the data out from `dest`:
204 let tmp = read_ptr(dest);
206 // Now zero out `dest`:
207 zero_memory(dest, 1);
212 /// Transform a region pointer - &T - to an unsafe pointer - *T.
214 pub fn to_unsafe_ptr<T>(thing: &T) -> *T {
218 /// Transform a const region pointer - &const T - to a const unsafe pointer - *const T.
220 pub fn to_const_unsafe_ptr<T>(thing: &const T) -> *const T {
224 /// Transform a mutable region pointer - &mut T - to a mutable unsafe pointer - *mut T.
226 pub fn to_mut_unsafe_ptr<T>(thing: &mut T) -> *mut T {
231 Given a **T (pointer to an array of pointers),
232 iterate through each *T, up to the provided `len`,
233 passing to the provided callback function
235 SAFETY NOTE: Pointer-arithmetic. Dragons be here.
237 pub unsafe fn array_each_with_len<T>(arr: **T, len: uint, cb: &fn(*T)) {
238 debug!("array_each_with_len: before iterate");
239 if (arr as uint == 0) {
240 fail!("ptr::array_each_with_len failure: arr input is null pointer");
242 //let start_ptr = *arr;
243 for e in range(0, len) {
244 let n = offset(arr, e as int);
247 debug!("array_each_with_len: after iterate");
251 Given a null-pointer-terminated **T (pointer to
252 an array of pointers), iterate through each *T,
253 passing to the provided callback function
255 SAFETY NOTE: This will only work with a null-terminated
256 pointer array. Barely less-dodgey Pointer Arithmetic.
259 pub unsafe fn array_each<T>(arr: **T, cb: &fn(*T)) {
260 if (arr as uint == 0) {
261 fail!("ptr::array_each_with_len failure: arr input is null pointer");
263 let len = buf_len(arr);
264 debug!("array_each inferred len: %u",
266 array_each_with_len(arr, len, cb);
269 #[allow(missing_doc)]
270 pub trait RawPtr<T> {
271 fn is_null(&self) -> bool;
272 fn is_not_null(&self) -> bool;
273 unsafe fn to_option(&self) -> Option<&T>;
274 fn offset(&self, count: int) -> Self;
276 unsafe fn offset_inbounds(self, count: int) -> Self;
279 /// Extension methods for immutable pointers
280 impl<T> RawPtr<T> for *T {
281 /// Returns true if the pointer is equal to the null pointer.
283 fn is_null(&self) -> bool { is_null(*self) }
285 /// Returns true if the pointer is not equal to the null pointer.
287 fn is_not_null(&self) -> bool { is_not_null(*self) }
290 /// Returns `None` if the pointer is null, or else returns the value wrapped
295 /// While this method is useful for null-safety, it is important to note
296 /// that this is still an unsafe operation because the returned value could
297 /// be pointing to invalid memory.
300 unsafe fn to_option(&self) -> Option<&T> {
301 if self.is_null() { None } else {
302 Some(cast::transmute(*self))
306 /// Calculates the offset from a pointer.
308 fn offset(&self, count: int) -> *T { offset(*self, count) }
310 /// Calculates the offset from a pointer. The offset *must* be in-bounds of
311 /// the object, or one-byte-past-the-end.
314 unsafe fn offset_inbounds(self, count: int) -> *T {
315 intrinsics::offset_inbounds(self, count)
319 /// Extension methods for mutable pointers
320 impl<T> RawPtr<T> for *mut T {
321 /// Returns true if the pointer is equal to the null pointer.
323 fn is_null(&self) -> bool { is_null(*self) }
325 /// Returns true if the pointer is not equal to the null pointer.
327 fn is_not_null(&self) -> bool { is_not_null(*self) }
330 /// Returns `None` if the pointer is null, or else returns the value wrapped
335 /// While this method is useful for null-safety, it is important to note
336 /// that this is still an unsafe operation because the returned value could
337 /// be pointing to invalid memory.
340 unsafe fn to_option(&self) -> Option<&T> {
341 if self.is_null() { None } else {
342 Some(cast::transmute(*self))
346 /// Calculates the offset from a mutable pointer.
348 fn offset(&self, count: int) -> *mut T { mut_offset(*self, count) }
350 /// Calculates the offset from a pointer. The offset *must* be in-bounds of
351 /// the object, or one-byte-past-the-end. An arithmetic overflow is also
352 /// undefined behaviour.
354 /// This method should be preferred over `offset` when the guarantee can be
355 /// satisfied, to enable better optimization.
358 unsafe fn offset_inbounds(self, count: int) -> *mut T {
359 intrinsics::offset_inbounds(self as *T, count) as *mut T
363 // Equality for pointers
365 impl<T> Eq for *const T {
367 fn eq(&self, other: &*const T) -> bool {
368 (*self as uint) == (*other as uint)
371 fn ne(&self, other: &*const T) -> bool { !self.eq(other) }
374 // Comparison for pointers
376 impl<T> Ord for *const T {
378 fn lt(&self, other: &*const T) -> bool {
379 (*self as uint) < (*other as uint)
382 fn le(&self, other: &*const T) -> bool {
383 (*self as uint) <= (*other as uint)
386 fn ge(&self, other: &*const T) -> bool {
387 (*self as uint) >= (*other as uint)
390 fn gt(&self, other: &*const T) -> bool {
391 (*self as uint) > (*other as uint)
396 impl<T, I: Int> Add<I, *T> for *T {
397 /// Add an integer value to a pointer to get an offset pointer.
398 /// Is calculated according to the size of the type pointed to.
400 pub fn add(&self, rhs: &I) -> *T {
401 self.offset(rhs.to_int() as int)
406 impl<T, I: Int> Sub<I, *T> for *T {
407 /// Subtract an integer value from a pointer to get an offset pointer.
408 /// Is calculated according to the size of the type pointed to.
410 pub fn sub(&self, rhs: &I) -> *T {
411 self.offset(-rhs.to_int() as int)
416 impl<T, I: Int> Add<I, *mut T> for *mut T {
417 /// Add an integer value to a pointer to get an offset pointer.
418 /// Is calculated according to the size of the type pointed to.
420 pub fn add(&self, rhs: &I) -> *mut T {
421 self.offset(rhs.to_int() as int)
426 impl<T, I: Int> Sub<I, *mut T> for *mut T {
427 /// Subtract an integer value from a pointer to get an offset pointer.
428 /// Is calculated according to the size of the type pointed to.
430 pub fn sub(&self, rhs: &I) -> *mut T {
431 self.offset(-rhs.to_int() as int)
452 let mut p = Pair {fst: 10, snd: 20};
453 let pptr: *mut Pair = &mut p;
454 let iptr: *mut int = cast::transmute(pptr);
455 assert_eq!(*iptr, 10);
457 assert_eq!(*iptr, 30);
458 assert_eq!(p.fst, 30);
460 *pptr = Pair {fst: 50, snd: 60};
461 assert_eq!(*iptr, 50);
462 assert_eq!(p.fst, 50);
463 assert_eq!(p.snd, 60);
465 let v0 = ~[32000u16, 32001u16, 32002u16];
466 let mut v1 = ~[0u16, 0u16, 0u16];
468 copy_memory(mut_offset(vec::raw::to_mut_ptr(v1), 1),
469 offset(vec::raw::to_ptr(v0), 1), 1);
470 assert!((v1[0] == 0u16 && v1[1] == 32001u16 && v1[2] == 0u16));
471 copy_memory(vec::raw::to_mut_ptr(v1),
472 offset(vec::raw::to_ptr(v0), 2), 1);
473 assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
475 copy_memory(mut_offset(vec::raw::to_mut_ptr(v1), 2),
476 vec::raw::to_ptr(v0), 1u);
477 assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
488 assert!(2u == s.as_c_str(|p| position(p, |c| *c == 'l' as c_char)));
489 assert!(4u == s.as_c_str(|p| position(p, |c| *c == 'o' as c_char)));
490 assert!(5u == s.as_c_str(|p| position(p, |c| *c == 0 as c_char)));
499 do s0.as_c_str |p0| {
500 do s1.as_c_str |p1| {
501 do s2.as_c_str |p2| {
502 let v = ~[p0, p1, p2, null()];
503 do v.as_imm_buf |vp, len| {
504 assert_eq!(unsafe { buf_len(vp) }, 3u);
514 let p: *int = null();
515 assert!(p.is_null());
516 assert!(!p.is_not_null());
518 let q = offset(p, 1);
519 assert!(!q.is_null());
520 assert!(q.is_not_null());
522 let mp: *mut int = mut_null();
523 assert!(mp.is_null());
524 assert!(!mp.is_not_null());
526 let mq = mp.offset(1);
527 assert!(!mq.is_null());
528 assert!(mq.is_not_null());
532 fn test_to_option() {
534 let p: *int = null();
535 assert_eq!(p.to_option(), None);
538 assert_eq!(q.to_option().unwrap(), &2);
540 let p: *mut int = mut_null();
541 assert_eq!(p.to_option(), None);
543 let q: *mut int = &mut 2;
544 assert_eq!(q.to_option().unwrap(), &2);
549 fn test_ptr_addition() {
554 let mut ptr = to_ptr(xs);
562 let mut xs_mut = xs.clone();
563 let mut m_ptr = to_mut_ptr(xs_mut);
564 let m_end = m_ptr + 16i16;
566 while m_ptr < m_end {
571 assert_eq!(xs_mut, ~[10, ..16]);
576 fn test_ptr_subtraction() {
580 let xs = ~[0,1,2,3,4,5,6,7,8,9];
582 let ptr = to_ptr(xs);
585 assert_eq!(*(ptr + idx), idx as int);
589 let mut xs_mut = xs.clone();
590 let m_start = to_mut_ptr(xs_mut);
591 let mut m_ptr = m_start + 9u32;
593 while m_ptr >= m_start {
598 assert_eq!(xs_mut, ~[0,2,4,6,8,10,12,14,16,18]);
603 fn test_ptr_array_each_with_len() {
607 let three = ~"threeThree";
609 ::cast::transmute(&one[0]),
610 ::cast::transmute(&two[0]),
611 ::cast::transmute(&three[0]),
616 let arr_ptr = &arr[0];
618 let mut iteration_count = 0;
619 array_each_with_len(arr_ptr, arr.len(),
621 let actual = str::raw::from_c_str(e);
622 let expected = expected_arr[ctr].clone();
624 "test_ptr_array_each e: %s, a: %s",
626 assert_eq!(actual, expected);
628 iteration_count += 1;
630 assert_eq!(iteration_count, 3u);
634 fn test_ptr_array_each() {
638 let three = ~"threeThree";
640 ::cast::transmute(&one[0]),
641 ::cast::transmute(&two[0]),
642 ::cast::transmute(&three[0]),
643 // fake a null terminator
649 let arr_ptr = &arr[0];
651 let mut iteration_count = 0;
652 array_each(arr_ptr, |e| {
653 let actual = str::raw::from_c_str(e);
654 let expected = expected_arr[ctr].clone();
656 "test_ptr_array_each e: %s, a: %s",
658 assert_eq!(actual, expected);
660 iteration_count += 1;
662 assert_eq!(iteration_count, 3);
667 #[ignore(cfg(windows))]
668 fn test_ptr_array_each_with_len_null_ptr() {
670 array_each_with_len(0 as **libc::c_char, 1, |e| {
671 str::raw::from_c_str(e);
677 #[ignore(cfg(windows))]
678 fn test_ptr_array_each_null_ptr() {
680 array_each(0 as **libc::c_char, |e| {
681 str::raw::from_c_str(e);
687 fn test_set_memory() {
688 let mut xs = [0u8, ..20];
689 let ptr = vec::raw::to_mut_ptr(xs);
690 unsafe { set_memory(ptr, 5u8, xs.len()); }
691 assert_eq!(xs, [5u8, ..20]);