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.
25 /// The `count` argument is in units of T; e.g. a `count` of 3
26 /// represents a pointer offset of `3 * sizeof::<T>()` bytes.
28 pub unsafe fn offset<T>(ptr: *T, count: int) -> *T {
29 intrinsics::offset(ptr, count)
32 /// Calculate the offset from a mut pointer. The count *must* be in bounds or
33 /// otherwise the loads of this address are undefined.
34 /// The `count` argument is in units of T; e.g. a `count` of 3
35 /// represents a pointer offset of `3 * sizeof::<T>()` bytes.
37 pub unsafe fn mut_offset<T>(ptr: *mut T, count: int) -> *mut T {
38 intrinsics::offset(ptr as *T, count) as *mut T
41 /// Return the offset of the first null pointer in `buf`.
43 pub unsafe fn buf_len<T>(buf: **T) -> uint {
44 position(buf, |i| *i == null())
47 impl<T> Clone for *T {
49 fn clone(&self) -> *T {
54 impl<T> Clone for *mut T {
56 fn clone(&self) -> *mut T {
61 /// Return the first offset `i` such that `f(buf[i]) == true`.
63 pub unsafe fn position<T>(buf: *T, f: |&T| -> bool) -> uint {
66 if f(&(*offset(buf, i as int))) { return i; }
71 /// Create an unsafe null pointer
73 pub fn null<T>() -> *T { 0 as *T }
75 /// Create an unsafe mutable null pointer
77 pub fn mut_null<T>() -> *mut T { 0 as *mut T }
79 /// Returns true if the pointer is equal to the null pointer.
81 pub fn is_null<T,P:RawPtr<T>>(ptr: P) -> bool { ptr.is_null() }
83 /// Returns true if the pointer is not equal to the null pointer.
85 pub fn is_not_null<T,P:RawPtr<T>>(ptr: P) -> bool { ptr.is_not_null() }
88 * Copies data from one location to another.
90 * Copies `count` elements (not bytes) from `src` to `dst`. The source
91 * and destination may overlap.
94 pub unsafe fn copy_memory<T,P:RawPtr<T>>(dst: *mut T, src: P, count: uint) {
95 intrinsics::copy_memory(dst, cast::transmute_immut_unsafe(src), count)
99 * Copies data from one location to another.
101 * Copies `count` elements (not bytes) from `src` to `dst`. The source
102 * and destination may *not* overlap.
105 pub unsafe fn copy_nonoverlapping_memory<T,P:RawPtr<T>>(dst: *mut T,
108 intrinsics::copy_nonoverlapping_memory(dst, cast::transmute_immut_unsafe(src), count)
112 * Invokes memset on the specified pointer, setting `count * size_of::<T>()`
113 * bytes of memory starting at `dst` to `c`.
116 pub unsafe fn set_memory<T>(dst: *mut T, c: u8, count: uint) {
117 intrinsics::set_memory(dst, c, count)
121 * Zeroes out `count * size_of::<T>` bytes of memory at `dst`
124 pub unsafe fn zero_memory<T>(dst: *mut T, count: uint) {
125 set_memory(dst, 0, count);
129 * Swap the values at two mutable locations of the same type, without
130 * deinitialising or copying either one.
133 pub unsafe fn swap_ptr<T>(x: *mut T, y: *mut T) {
134 // Give ourselves some scratch space to work with
135 let mut tmp: T = intrinsics::uninit();
136 let t: *mut T = &mut tmp;
139 copy_nonoverlapping_memory(t, x, 1);
140 copy_memory(x, y, 1); // `x` and `y` may overlap
141 copy_nonoverlapping_memory(y, t, 1);
143 // y and t now point to the same thing, but we need to completely forget `tmp`
144 // because it's no longer relevant.
149 * Replace the value at a mutable location with a new one, returning the old
150 * value, without deinitialising or copying either one.
153 pub unsafe fn replace_ptr<T>(dest: *mut T, mut src: T) -> T {
154 swap(cast::transmute(dest), &mut src); // cannot overlap
159 * Reads the value from `*src` and returns it. Does not copy `*src`.
162 pub unsafe fn read_ptr<T>(src: *T) -> T {
163 let mut tmp: T = intrinsics::uninit();
164 copy_nonoverlapping_memory(&mut tmp, src, 1);
169 * Reads the value from `*src` and nulls it out.
170 * This currently prevents destructors from executing.
173 pub unsafe fn read_and_zero_ptr<T>(dest: *mut T) -> T {
174 // Copy the data out from `dest`:
175 let tmp = read_ptr(&*dest);
177 // Now zero out `dest`:
178 zero_memory(dest, 1);
183 /// Transform a region pointer - &T - to an unsafe pointer - *T.
185 pub fn to_unsafe_ptr<T>(thing: &T) -> *T {
189 /// Transform a mutable region pointer - &mut T - to a mutable unsafe pointer - *mut T.
191 pub fn to_mut_unsafe_ptr<T>(thing: &mut T) -> *mut T {
196 Given a **T (pointer to an array of pointers),
197 iterate through each *T, up to the provided `len`,
198 passing to the provided callback function
200 SAFETY NOTE: Pointer-arithmetic. Dragons be here.
202 pub unsafe fn array_each_with_len<T>(arr: **T, len: uint, cb: |*T|) {
203 debug!("array_each_with_len: before iterate");
204 if (arr as uint == 0) {
205 fail!("ptr::array_each_with_len failure: arr input is null pointer");
207 //let start_ptr = *arr;
208 for e in range(0, len) {
209 let n = offset(arr, e as int);
212 debug!("array_each_with_len: after iterate");
216 Given a null-pointer-terminated **T (pointer to
217 an array of pointers), iterate through each *T,
218 passing to the provided callback function
220 SAFETY NOTE: This will only work with a null-terminated
221 pointer array. Barely less-dodgy Pointer Arithmetic.
224 pub unsafe fn array_each<T>(arr: **T, cb: |*T|) {
225 if (arr as uint == 0) {
226 fail!("ptr::array_each_with_len failure: arr input is null pointer");
228 let len = buf_len(arr);
229 debug!("array_each inferred len: {}", len);
230 array_each_with_len(arr, len, cb);
233 #[allow(missing_doc)]
234 pub trait RawPtr<T> {
236 fn is_null(&self) -> bool;
237 fn is_not_null(&self) -> bool;
238 fn to_uint(&self) -> uint;
239 unsafe fn to_option(&self) -> Option<&T>;
240 unsafe fn offset(self, count: int) -> Self;
243 /// Extension methods for immutable pointers
244 impl<T> RawPtr<T> for *T {
245 /// Returns the null pointer.
247 fn null() -> *T { null() }
249 /// Returns true if the pointer is equal to the null pointer.
251 fn is_null(&self) -> bool { *self == RawPtr::null() }
253 /// Returns true if the pointer is not equal to the null pointer.
255 fn is_not_null(&self) -> bool { *self != RawPtr::null() }
257 /// Returns the address of this pointer.
259 fn to_uint(&self) -> uint { *self as uint }
262 /// Returns `None` if the pointer is null, or else returns the value wrapped
267 /// While this method is useful for null-safety, it is important to note
268 /// that this is still an unsafe operation because the returned value could
269 /// be pointing to invalid memory.
272 unsafe fn to_option(&self) -> Option<&T> {
273 if self.is_null() { None } else {
274 Some(cast::transmute(*self))
278 /// Calculates the offset from a pointer. The offset *must* be in-bounds of
279 /// the object, or one-byte-past-the-end.
281 unsafe fn offset(self, count: int) -> *T { offset(self, count) }
284 /// Extension methods for mutable pointers
285 impl<T> RawPtr<T> for *mut T {
286 /// Returns the null pointer.
288 fn null() -> *mut T { mut_null() }
290 /// Returns true if the pointer is equal to the null pointer.
292 fn is_null(&self) -> bool { *self == RawPtr::null() }
294 /// Returns true if the pointer is not equal to the null pointer.
296 fn is_not_null(&self) -> bool { *self != RawPtr::null() }
298 /// Returns the address of this pointer.
300 fn to_uint(&self) -> uint { *self as uint }
303 /// Returns `None` if the pointer is null, or else returns the value wrapped
308 /// While this method is useful for null-safety, it is important to note
309 /// that this is still an unsafe operation because the returned value could
310 /// be pointing to invalid memory.
313 unsafe fn to_option(&self) -> Option<&T> {
314 if self.is_null() { None } else {
315 Some(cast::transmute(*self))
319 /// Calculates the offset from a pointer. The offset *must* be in-bounds of
320 /// the object, or one-byte-past-the-end. An arithmetic overflow is also
321 /// undefined behaviour.
323 /// This method should be preferred over `offset` when the guarantee can be
324 /// satisfied, to enable better optimization.
326 unsafe fn offset(self, count: int) -> *mut T { mut_offset(self, count) }
329 // Equality for pointers
333 fn eq(&self, other: &*T) -> bool {
337 fn ne(&self, other: &*T) -> bool { !self.eq(other) }
341 impl<T> Eq for *mut T {
343 fn eq(&self, other: &*mut T) -> bool {
347 fn ne(&self, other: &*mut T) -> bool { !self.eq(other) }
350 // Equivalence for pointers
352 impl<T> Equiv<*mut T> for *T {
353 fn equiv(&self, other: &*mut T) -> bool {
354 self.to_uint() == other.to_uint()
359 impl<T> Equiv<*T> for *mut T {
360 fn equiv(&self, other: &*T) -> bool {
361 self.to_uint() == other.to_uint()
365 // Equality for extern "C" fn pointers
367 mod externfnpointers {
371 impl<_R> Eq for extern "C" fn() -> _R {
373 fn eq(&self, other: &extern "C" fn() -> _R) -> bool {
374 let self_: *() = unsafe { cast::transmute(*self) };
375 let other_: *() = unsafe { cast::transmute(*other) };
379 fn ne(&self, other: &extern "C" fn() -> _R) -> bool {
383 macro_rules! fnptreq(
385 impl<_R,$($p),*> Eq for extern "C" fn($($p),*) -> _R {
387 fn eq(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
388 let self_: *() = unsafe { cast::transmute(*self) };
389 let other_: *() = unsafe { cast::transmute(*other) };
393 fn ne(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
406 // Comparison for pointers
410 fn lt(&self, other: &*T) -> bool {
414 fn le(&self, other: &*T) -> bool {
418 fn ge(&self, other: &*T) -> bool {
422 fn gt(&self, other: &*T) -> bool {
428 impl<T> Ord for *mut T {
430 fn lt(&self, other: &*mut T) -> bool {
434 fn le(&self, other: &*mut T) -> bool {
438 fn ge(&self, other: &*mut T) -> bool {
442 fn gt(&self, other: &*mut T) -> bool {
456 use vec::{ImmutableVector, MutableVector};
465 let mut p = Pair {fst: 10, snd: 20};
466 let pptr: *mut Pair = &mut p;
467 let iptr: *mut int = cast::transmute(pptr);
468 assert_eq!(*iptr, 10);
470 assert_eq!(*iptr, 30);
471 assert_eq!(p.fst, 30);
473 *pptr = Pair {fst: 50, snd: 60};
474 assert_eq!(*iptr, 50);
475 assert_eq!(p.fst, 50);
476 assert_eq!(p.snd, 60);
478 let v0 = ~[32000u16, 32001u16, 32002u16];
479 let mut v1 = ~[0u16, 0u16, 0u16];
481 copy_memory(mut_offset(v1.as_mut_ptr(), 1),
482 offset(v0.as_ptr(), 1), 1);
483 assert!((v1[0] == 0u16 && v1[1] == 32001u16 && v1[2] == 0u16));
484 copy_memory(v1.as_mut_ptr(),
485 offset(v0.as_ptr(), 2), 1);
486 assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
488 copy_memory(mut_offset(v1.as_mut_ptr(), 2),
490 assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
499 "hello".with_c_str(|p| {
501 assert!(2u == position(p, |c| *c == 'l' as c_char));
502 assert!(4u == position(p, |c| *c == 'o' as c_char));
503 assert!(5u == position(p, |c| *c == 0 as c_char));
510 "hello".with_c_str(|p0| {
511 "there".with_c_str(|p1| {
512 "thing".with_c_str(|p2| {
513 let v = ~[p0, p1, p2, null()];
515 assert_eq!(buf_len(v.as_ptr()), 3u);
524 let p: *int = null();
525 assert!(p.is_null());
526 assert!(!p.is_not_null());
528 let q = unsafe { offset(p, 1) };
529 assert!(!q.is_null());
530 assert!(q.is_not_null());
532 let mp: *mut int = mut_null();
533 assert!(mp.is_null());
534 assert!(!mp.is_not_null());
536 let mq = unsafe { mp.offset(1) };
537 assert!(!mq.is_null());
538 assert!(mq.is_not_null());
542 fn test_to_option() {
544 let p: *int = null();
545 assert_eq!(p.to_option(), None);
548 assert_eq!(q.to_option().unwrap(), &2);
550 let p: *mut int = mut_null();
551 assert_eq!(p.to_option(), None);
553 let q: *mut int = &mut 2;
554 assert_eq!(q.to_option().unwrap(), &2);
559 fn test_ptr_addition() {
562 let mut ptr = xs.as_ptr();
563 let end = ptr.offset(16);
570 let mut xs_mut = xs.clone();
571 let mut m_ptr = xs_mut.as_mut_ptr();
572 let m_end = m_ptr.offset(16);
574 while m_ptr < m_end {
576 m_ptr = m_ptr.offset(1);
579 assert_eq!(xs_mut, ~[10, ..16]);
584 fn test_ptr_subtraction() {
586 let xs = ~[0,1,2,3,4,5,6,7,8,9];
588 let ptr = xs.as_ptr();
591 assert_eq!(*(ptr.offset(idx as int)), idx as int);
595 let mut xs_mut = xs.clone();
596 let m_start = xs_mut.as_mut_ptr();
597 let mut m_ptr = m_start.offset(9);
599 while m_ptr >= m_start {
601 m_ptr = m_ptr.offset(-1);
604 assert_eq!(xs_mut, ~[0,2,4,6,8,10,12,14,16,18]);
609 fn test_ptr_array_each_with_len() {
611 let one = "oneOne".to_c_str();
612 let two = "twoTwo".to_c_str();
613 let three = "threeThree".to_c_str();
615 one.with_ref(|buf| buf),
616 two.with_ref(|buf| buf),
617 three.with_ref(|buf| buf),
624 let mut iteration_count = 0;
625 array_each_with_len(arr.as_ptr(), arr.len(), |e| {
626 let actual = str::raw::from_c_str(e);
627 let expected = expected_arr[ctr].with_ref(|buf| {
628 str::raw::from_c_str(buf)
631 "test_ptr_array_each_with_len e: {}, a: {}",
633 assert_eq!(actual, expected);
635 iteration_count += 1;
637 assert_eq!(iteration_count, 3u);
642 fn test_ptr_array_each() {
644 let one = "oneOne".to_c_str();
645 let two = "twoTwo".to_c_str();
646 let three = "threeThree".to_c_str();
648 one.with_ref(|buf| buf),
649 two.with_ref(|buf| buf),
650 three.with_ref(|buf| buf),
651 // fake a null terminator
658 let arr_ptr = arr.as_ptr();
660 let mut iteration_count = 0;
661 array_each(arr_ptr, |e| {
662 let actual = str::raw::from_c_str(e);
663 let expected = expected_arr[ctr].with_ref(|buf| {
664 str::raw::from_c_str(buf)
667 "test_ptr_array_each e: {}, a: {}",
669 assert_eq!(actual, expected);
671 iteration_count += 1;
673 assert_eq!(iteration_count, 3);
679 fn test_ptr_array_each_with_len_null_ptr() {
681 array_each_with_len(0 as **libc::c_char, 1, |e| {
682 str::raw::from_c_str(e);
688 fn test_ptr_array_each_null_ptr() {
690 array_each(0 as **libc::c_char, |e| {
691 str::raw::from_c_str(e);
697 fn test_set_memory() {
698 let mut xs = [0u8, ..20];
699 let ptr = xs.as_mut_ptr();
700 unsafe { set_memory(ptr, 5u8, xs.len()); }
701 assert_eq!(xs, [5u8, ..20]);