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};
18 use option::{Option, Some, None};
19 use unstable::intrinsics;
22 #[cfg(not(test))] use cmp::{Eq, Ord};
24 /// Calculate the offset from a pointer
26 pub unsafe fn offset<T>(ptr: *T, count: int) -> *T {
27 intrinsics::offset(ptr, count)
30 /// Calculate the offset from a mut pointer. The count *must* be in bounds or
31 /// otherwise the loads of this address are undefined.
33 pub unsafe fn mut_offset<T>(ptr: *mut T, count: int) -> *mut T {
34 intrinsics::offset(ptr as *T, count) as *mut T
37 /// Return the offset of the first null pointer in `buf`.
39 pub unsafe fn buf_len<T>(buf: **T) -> uint {
40 position(buf, |i| *i == null())
43 impl<T> Clone for *T {
45 fn clone(&self) -> *T {
50 /// Return the first offset `i` such that `f(buf[i]) == true`.
52 pub unsafe fn position<T>(buf: *T, f: &fn(&T) -> bool) -> uint {
55 if f(&(*offset(buf, i as int))) { return i; }
60 /// Create an unsafe null pointer
62 pub fn null<T>() -> *T { 0 as *T }
64 /// Create an unsafe mutable null pointer
66 pub fn mut_null<T>() -> *mut T { 0 as *mut T }
68 /// Returns true if the pointer is equal to the null pointer.
70 pub fn is_null<T,P:RawPtr<T>>(ptr: P) -> bool { ptr.is_null() }
72 /// Returns true if the pointer is not equal to the null pointer.
74 pub fn is_not_null<T,P:RawPtr<T>>(ptr: P) -> bool { ptr.is_not_null() }
77 * Copies data from one location to another.
79 * Copies `count` elements (not bytes) from `src` to `dst`. The source
80 * and destination may overlap.
83 #[cfg(target_word_size = "32")]
84 pub unsafe fn copy_memory<T,P:RawPtr<T>>(dst: *mut T, src: P, count: uint) {
85 intrinsics::memmove32(dst,
86 cast::transmute_immut_unsafe(src),
91 * Copies data from one location to another.
93 * Copies `count` elements (not bytes) from `src` to `dst`. The source
94 * and destination may overlap.
97 #[cfg(target_word_size = "64")]
98 pub unsafe fn copy_memory<T,P:RawPtr<T>>(dst: *mut T, src: P, count: uint) {
99 intrinsics::memmove64(dst,
100 cast::transmute_immut_unsafe(src),
105 * Copies data from one location to another.
107 * Copies `count` elements (not bytes) from `src` to `dst`. The source
108 * and destination may *not* overlap.
111 #[cfg(target_word_size = "32")]
112 pub unsafe fn copy_nonoverlapping_memory<T,P:RawPtr<T>>(dst: *mut T,
115 intrinsics::memcpy32(dst,
116 cast::transmute_immut_unsafe(src),
121 * Copies data from one location to another.
123 * Copies `count` elements (not bytes) from `src` to `dst`. The source
124 * and destination may *not* overlap.
127 #[cfg(target_word_size = "64")]
128 pub unsafe fn copy_nonoverlapping_memory<T,P:RawPtr<T>>(dst: *mut T,
131 intrinsics::memcpy64(dst,
132 cast::transmute_immut_unsafe(src),
137 * Invokes memset on the specified pointer, setting `count * size_of::<T>()`
138 * bytes of memory starting at `dst` to `c`.
141 #[cfg(target_word_size = "32")]
142 pub unsafe fn set_memory<T>(dst: *mut T, c: u8, count: uint) {
143 intrinsics::memset32(dst, c, count as u32);
147 * Invokes memset on the specified pointer, setting `count * size_of::<T>()`
148 * bytes of memory starting at `dst` to `c`.
151 #[cfg(target_word_size = "64")]
152 pub unsafe fn set_memory<T>(dst: *mut T, c: u8, count: uint) {
153 intrinsics::memset64(dst, c, count as u64);
157 * Zeroes out `count * size_of::<T>` bytes of memory at `dst`
160 pub unsafe fn zero_memory<T>(dst: *mut T, count: uint) {
161 set_memory(dst, 0, count);
165 * Swap the values at two mutable locations of the same type, without
166 * deinitialising or copying either one.
169 pub unsafe fn swap_ptr<T>(x: *mut T, y: *mut T) {
170 // Give ourselves some scratch space to work with
171 let mut tmp: T = intrinsics::uninit();
172 let t: *mut T = &mut tmp;
175 copy_nonoverlapping_memory(t, x, 1);
176 copy_memory(x, y, 1); // `x` and `y` may overlap
177 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.
185 * Replace the value at a mutable location with a new one, returning the old
186 * value, without deinitialising or copying either one.
189 pub unsafe fn replace_ptr<T>(dest: *mut T, mut src: T) -> T {
190 swap(cast::transmute(dest), &mut src); // cannot overlap
195 * Reads the value from `*src` and returns it. Does not copy `*src`.
198 pub unsafe fn read_ptr<T>(src: *mut T) -> T {
199 let mut tmp: T = intrinsics::uninit();
200 copy_nonoverlapping_memory(&mut tmp, src, 1);
205 * Reads the value from `*src` and nulls it out.
206 * This currently prevents destructors from executing.
209 pub unsafe fn read_and_zero_ptr<T>(dest: *mut T) -> T {
210 // Copy the data out from `dest`:
211 let tmp = read_ptr(dest);
213 // Now zero out `dest`:
214 zero_memory(dest, 1);
219 /// Transform a region pointer - &T - to an unsafe pointer - *T.
221 pub fn to_unsafe_ptr<T>(thing: &T) -> *T {
225 /// Transform a mutable region pointer - &mut T - to a mutable unsafe pointer - *mut T.
227 pub fn to_mut_unsafe_ptr<T>(thing: &mut T) -> *mut T {
232 Given a **T (pointer to an array of pointers),
233 iterate through each *T, up to the provided `len`,
234 passing to the provided callback function
236 SAFETY NOTE: Pointer-arithmetic. Dragons be here.
238 pub unsafe fn array_each_with_len<T>(arr: **T, len: uint, cb: &fn(*T)) {
239 debug!("array_each_with_len: before iterate");
240 if (arr as uint == 0) {
241 fail!("ptr::array_each_with_len failure: arr input is null pointer");
243 //let start_ptr = *arr;
244 for e in range(0, len) {
245 let n = offset(arr, e as int);
248 debug!("array_each_with_len: after iterate");
252 Given a null-pointer-terminated **T (pointer to
253 an array of pointers), iterate through each *T,
254 passing to the provided callback function
256 SAFETY NOTE: This will only work with a null-terminated
257 pointer array. Barely less-dodgy Pointer Arithmetic.
260 pub unsafe fn array_each<T>(arr: **T, cb: &fn(*T)) {
261 if (arr as uint == 0) {
262 fail!("ptr::array_each_with_len failure: arr input is null pointer");
264 let len = buf_len(arr);
265 debug!("array_each inferred len: %u",
267 array_each_with_len(arr, len, cb);
270 #[allow(missing_doc)]
271 pub trait RawPtr<T> {
273 fn is_null(&self) -> bool;
274 fn is_not_null(&self) -> bool;
275 fn to_uint(&self) -> uint;
276 unsafe fn to_option(&self) -> Option<&T>;
277 unsafe fn offset(self, count: int) -> Self;
280 /// Extension methods for immutable pointers
281 impl<T> RawPtr<T> for *T {
282 /// Returns the null pointer.
284 fn null() -> *T { null() }
286 /// Returns true if the pointer is equal to the null pointer.
288 fn is_null(&self) -> bool { *self == RawPtr::null() }
290 /// Returns true if the pointer is not equal to the null pointer.
292 fn is_not_null(&self) -> bool { *self != RawPtr::null() }
294 /// Returns the address of this pointer.
296 fn to_uint(&self) -> uint { *self as uint }
299 /// Returns `None` if the pointer is null, or else returns the value wrapped
304 /// While this method is useful for null-safety, it is important to note
305 /// that this is still an unsafe operation because the returned value could
306 /// be pointing to invalid memory.
309 unsafe fn to_option(&self) -> Option<&T> {
310 if self.is_null() { None } else {
311 Some(cast::transmute(*self))
315 /// Calculates the offset from a pointer. The offset *must* be in-bounds of
316 /// the object, or one-byte-past-the-end.
318 unsafe fn offset(self, count: int) -> *T { offset(self, count) }
321 /// Extension methods for mutable pointers
322 impl<T> RawPtr<T> for *mut T {
323 /// Returns the null pointer.
325 fn null() -> *mut T { mut_null() }
327 /// Returns true if the pointer is equal to the null pointer.
329 fn is_null(&self) -> bool { *self == RawPtr::null() }
331 /// Returns true if the pointer is not equal to the null pointer.
333 fn is_not_null(&self) -> bool { *self != RawPtr::null() }
335 /// Returns the address of this pointer.
337 fn to_uint(&self) -> uint { *self as uint }
340 /// Returns `None` if the pointer is null, or else returns the value wrapped
345 /// While this method is useful for null-safety, it is important to note
346 /// that this is still an unsafe operation because the returned value could
347 /// be pointing to invalid memory.
350 unsafe fn to_option(&self) -> Option<&T> {
351 if self.is_null() { None } else {
352 Some(cast::transmute(*self))
356 /// Calculates the offset from a pointer. The offset *must* be in-bounds of
357 /// the object, or one-byte-past-the-end. An arithmetic overflow is also
358 /// undefined behaviour.
360 /// This method should be preferred over `offset` when the guarantee can be
361 /// satisfied, to enable better optimization.
363 unsafe fn offset(self, count: int) -> *mut T { mut_offset(self, count) }
366 // Equality for pointers
370 fn eq(&self, other: &*T) -> bool {
374 fn ne(&self, other: &*T) -> bool { !self.eq(other) }
378 impl<T> Eq for *mut T {
380 fn eq(&self, other: &*mut T) -> bool {
384 fn ne(&self, other: &*mut T) -> bool { !self.eq(other) }
387 // Equivalence for pointers
389 impl<T> Equiv<*mut T> for *T {
390 fn equiv(&self, other: &*mut T) -> bool {
391 self.to_uint() == other.to_uint()
396 impl<T> Equiv<*T> for *mut T {
397 fn equiv(&self, other: &*T) -> bool {
398 self.to_uint() == other.to_uint()
402 // Equality for extern "C" fn pointers
404 mod externfnpointers {
408 impl<_R> Eq for extern "C" fn() -> _R {
410 fn eq(&self, other: &extern "C" fn() -> _R) -> bool {
411 let self_: *() = unsafe { cast::transmute(*self) };
412 let other_: *() = unsafe { cast::transmute(*other) };
416 fn ne(&self, other: &extern "C" fn() -> _R) -> bool {
420 macro_rules! fnptreq(
422 impl<_R,$($p),*> Eq for extern "C" fn($($p),*) -> _R {
424 fn eq(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
425 let self_: *() = unsafe { cast::transmute(*self) };
426 let other_: *() = unsafe { cast::transmute(*other) };
430 fn ne(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
443 // Comparison for pointers
447 fn lt(&self, other: &*T) -> bool {
451 fn le(&self, other: &*T) -> bool {
455 fn ge(&self, other: &*T) -> bool {
459 fn gt(&self, other: &*T) -> bool {
465 impl<T> Ord for *mut T {
467 fn lt(&self, other: &*mut T) -> bool {
471 fn le(&self, other: &*mut T) -> bool {
475 fn ge(&self, other: &*mut T) -> bool {
479 fn gt(&self, other: &*mut T) -> bool {
502 let mut p = Pair {fst: 10, snd: 20};
503 let pptr: *mut Pair = &mut p;
504 let iptr: *mut int = cast::transmute(pptr);
505 assert_eq!(*iptr, 10);
507 assert_eq!(*iptr, 30);
508 assert_eq!(p.fst, 30);
510 *pptr = Pair {fst: 50, snd: 60};
511 assert_eq!(*iptr, 50);
512 assert_eq!(p.fst, 50);
513 assert_eq!(p.snd, 60);
515 let v0 = ~[32000u16, 32001u16, 32002u16];
516 let mut v1 = ~[0u16, 0u16, 0u16];
518 copy_memory(mut_offset(vec::raw::to_mut_ptr(v1), 1),
519 offset(vec::raw::to_ptr(v0), 1), 1);
520 assert!((v1[0] == 0u16 && v1[1] == 32001u16 && v1[2] == 0u16));
521 copy_memory(vec::raw::to_mut_ptr(v1),
522 offset(vec::raw::to_ptr(v0), 2), 1);
523 assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
525 copy_memory(mut_offset(vec::raw::to_mut_ptr(v1), 2),
526 vec::raw::to_ptr(v0), 1u);
527 assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
536 do "hello".with_c_str |p| {
538 assert!(2u == position(p, |c| *c == 'l' as c_char));
539 assert!(4u == position(p, |c| *c == 'o' as c_char));
540 assert!(5u == position(p, |c| *c == 0 as c_char));
547 do "hello".with_c_str |p0| {
548 do "there".with_c_str |p1| {
549 do "thing".with_c_str |p2| {
550 let v = ~[p0, p1, p2, null()];
551 do v.as_imm_buf |vp, len| {
552 assert_eq!(unsafe { buf_len(vp) }, 3u);
562 let p: *int = null();
563 assert!(p.is_null());
564 assert!(!p.is_not_null());
566 let q = unsafe { offset(p, 1) };
567 assert!(!q.is_null());
568 assert!(q.is_not_null());
570 let mp: *mut int = mut_null();
571 assert!(mp.is_null());
572 assert!(!mp.is_not_null());
574 let mq = unsafe { mp.offset(1) };
575 assert!(!mq.is_null());
576 assert!(mq.is_not_null());
580 fn test_to_option() {
582 let p: *int = null();
583 assert_eq!(p.to_option(), None);
586 assert_eq!(q.to_option().unwrap(), &2);
588 let p: *mut int = mut_null();
589 assert_eq!(p.to_option(), None);
591 let q: *mut int = &mut 2;
592 assert_eq!(q.to_option().unwrap(), &2);
597 fn test_ptr_addition() {
602 let mut ptr = to_ptr(xs);
603 let end = ptr.offset(16);
610 let mut xs_mut = xs.clone();
611 let mut m_ptr = to_mut_ptr(xs_mut);
612 let m_end = m_ptr.offset(16);
614 while m_ptr < m_end {
616 m_ptr = m_ptr.offset(1);
619 assert_eq!(xs_mut, ~[10, ..16]);
624 fn test_ptr_subtraction() {
628 let xs = ~[0,1,2,3,4,5,6,7,8,9];
630 let ptr = to_ptr(xs);
633 assert_eq!(*(ptr.offset(idx as int)), idx as int);
637 let mut xs_mut = xs.clone();
638 let m_start = to_mut_ptr(xs_mut);
639 let mut m_ptr = m_start.offset(9);
641 while m_ptr >= m_start {
643 m_ptr = m_ptr.offset(-1);
646 assert_eq!(xs_mut, ~[0,2,4,6,8,10,12,14,16,18]);
651 fn test_ptr_array_each_with_len() {
653 let one = "oneOne".to_c_str();
654 let two = "twoTwo".to_c_str();
655 let three = "threeThree".to_c_str();
657 one.with_ref(|buf| buf),
658 two.with_ref(|buf| buf),
659 three.with_ref(|buf| buf),
665 do arr.as_imm_buf |arr_ptr, arr_len| {
667 let mut iteration_count = 0;
668 do array_each_with_len(arr_ptr, arr_len) |e| {
669 let actual = str::raw::from_c_str(e);
670 let expected = do expected_arr[ctr].with_ref |buf| {
671 str::raw::from_c_str(buf)
674 "test_ptr_array_each_with_len e: %s, a: %s",
676 assert_eq!(actual, expected);
678 iteration_count += 1;
680 assert_eq!(iteration_count, 3u);
686 fn test_ptr_array_each() {
688 let one = "oneOne".to_c_str();
689 let two = "twoTwo".to_c_str();
690 let three = "threeThree".to_c_str();
692 one.with_ref(|buf| buf),
693 two.with_ref(|buf| buf),
694 three.with_ref(|buf| buf),
695 // fake a null terminator
702 do arr.as_imm_buf |arr_ptr, _| {
704 let mut iteration_count = 0;
705 do array_each(arr_ptr) |e| {
706 let actual = str::raw::from_c_str(e);
707 let expected = do expected_arr[ctr].with_ref |buf| {
708 str::raw::from_c_str(buf)
711 "test_ptr_array_each e: %s, a: %s",
713 assert_eq!(actual, expected);
715 iteration_count += 1;
717 assert_eq!(iteration_count, 3);
724 fn test_ptr_array_each_with_len_null_ptr() {
726 array_each_with_len(0 as **libc::c_char, 1, |e| {
727 str::raw::from_c_str(e);
733 fn test_ptr_array_each_null_ptr() {
735 array_each(0 as **libc::c_char, |e| {
736 str::raw::from_c_str(e);
742 fn test_set_memory() {
743 let mut xs = [0u8, ..20];
744 let ptr = vec::raw::to_mut_ptr(xs);
745 unsafe { set_memory(ptr, 5u8, xs.len()); }
746 assert_eq!(xs, [5u8, ..20]);