]> git.lizzy.rs Git - rust.git/blob - src/libstd/ptr.rs
auto merge of #12530 : alexcrichton/rust/make-check-no-rpath, r=brson
[rust.git] / src / libstd / ptr.rs
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.
4 //
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.
10
11 //! Unsafe pointer utility functions
12
13 use cast;
14 use clone::Clone;
15 #[cfg(not(test))]
16 use cmp::Equiv;
17 use iter::{range, Iterator};
18 use mem;
19 use option::{Option, Some, None};
20 use intrinsics;
21
22 #[cfg(not(test))] use cmp::{Eq, Ord};
23
24 /// Return the offset of the first null pointer in `buf`.
25 #[inline]
26 pub unsafe fn buf_len<T>(buf: **T) -> uint {
27     position(buf, |i| *i == null())
28 }
29
30 impl<T> Clone for *T {
31     #[inline]
32     fn clone(&self) -> *T {
33         *self
34     }
35 }
36
37 impl<T> Clone for *mut T {
38     #[inline]
39     fn clone(&self) -> *mut T {
40         *self
41     }
42 }
43
44 /// Return the first offset `i` such that `f(buf[i]) == true`.
45 #[inline]
46 pub unsafe fn position<T>(buf: *T, f: |&T| -> bool) -> uint {
47     let mut i = 0;
48     loop {
49         if f(&(*buf.offset(i as int))) { return i; }
50         else { i += 1; }
51     }
52 }
53
54 /// Create an unsafe null pointer
55 #[inline]
56 pub fn null<T>() -> *T { 0 as *T }
57
58 /// Create an unsafe mutable null pointer
59 #[inline]
60 pub fn mut_null<T>() -> *mut T { 0 as *mut T }
61
62 /**
63  * Copies data from one location to another.
64  *
65  * Copies `count` elements (not bytes) from `src` to `dst`. The source
66  * and destination may overlap.
67  */
68 #[inline]
69 pub unsafe fn copy_memory<T>(dst: *mut T, src: *T, count: uint) {
70     intrinsics::copy_memory(dst, src, count)
71 }
72
73 /**
74  * Copies data from one location to another.
75  *
76  * Copies `count` elements (not bytes) from `src` to `dst`. The source
77  * and destination may *not* overlap.
78  */
79 #[inline]
80 pub unsafe fn copy_nonoverlapping_memory<T>(dst: *mut T,
81                                             src: *T,
82                                             count: uint) {
83     intrinsics::copy_nonoverlapping_memory(dst, src, count)
84 }
85
86 /**
87  * Invokes memset on the specified pointer, setting `count * size_of::<T>()`
88  * bytes of memory starting at `dst` to `c`.
89  */
90 #[inline]
91 pub unsafe fn set_memory<T>(dst: *mut T, c: u8, count: uint) {
92     intrinsics::set_memory(dst, c, count)
93 }
94
95 /**
96  * Zeroes out `count * size_of::<T>` bytes of memory at `dst`
97  */
98 #[inline]
99 pub unsafe fn zero_memory<T>(dst: *mut T, count: uint) {
100     set_memory(dst, 0, count);
101 }
102
103 /**
104  * Swap the values at two mutable locations of the same type, without
105  * deinitialising either. They may overlap.
106  */
107 #[inline]
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;
112
113     // Perform the swap
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);
117
118     // y and t now point to the same thing, but we need to completely forget `tmp`
119     // because it's no longer relevant.
120     cast::forget(tmp);
121 }
122
123 /**
124  * Replace the value at a mutable location with a new one, returning the old
125  * value, without deinitialising either.
126  */
127 #[inline]
128 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
129     mem::swap(cast::transmute(dest), &mut src); // cannot overlap
130     src
131 }
132
133 /**
134  * Reads the value from `*src` and returns it.
135  */
136 #[inline(always)]
137 pub unsafe fn read<T>(src: *T) -> T {
138     let mut tmp: T = mem::uninit();
139     copy_nonoverlapping_memory(&mut tmp, src, 1);
140     tmp
141 }
142
143 /**
144  * Reads the value from `*src` and nulls it out.
145  * This currently prevents destructors from executing.
146  */
147 #[inline(always)]
148 pub unsafe fn read_and_zero<T>(dest: *mut T) -> T {
149     // Copy the data out from `dest`:
150     let tmp = read(&*dest);
151
152     // Now zero out `dest`:
153     zero_memory(dest, 1);
154
155     tmp
156 }
157
158 /**
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
162
163   SAFETY NOTE: Pointer-arithmetic. Dragons be here.
164 */
165 pub unsafe fn array_each_with_len<T>(arr: **T, len: uint, cb: |*T|) {
166     debug!("array_each_with_len: before iterate");
167     if arr.is_null() {
168         fail!("ptr::array_each_with_len failure: arr input is null pointer");
169     }
170     //let start_ptr = *arr;
171     for e in range(0, len) {
172         let n = arr.offset(e as int);
173         cb(*n);
174     }
175     debug!("array_each_with_len: after iterate");
176 }
177
178 /**
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
182
183   SAFETY NOTE: This will only work with a null-terminated
184   pointer array. Barely less-dodgy Pointer Arithmetic.
185   Dragons be here.
186 */
187 pub unsafe fn array_each<T>(arr: **T, cb: |*T|) {
188     if arr.is_null()  {
189         fail!("ptr::array_each_with_len failure: arr input is null pointer");
190     }
191     let len = buf_len(arr);
192     debug!("array_each inferred len: {}", len);
193     array_each_with_len(arr, len, cb);
194 }
195
196 /// Extension methods for raw pointers.
197 pub trait RawPtr<T> {
198     /// Returns the null pointer.
199     fn null() -> Self;
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
207     /// in `Some`.
208     ///
209     /// # Safety Notes
210     ///
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.  `count` is in units of T; e.g. a
217     /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
218     unsafe fn offset(self, count: int) -> Self;
219 }
220
221 impl<T> RawPtr<T> for *T {
222     #[inline]
223     fn null() -> *T { null() }
224
225     #[inline]
226     fn is_null(&self) -> bool { *self == RawPtr::null() }
227
228     #[inline]
229     fn to_uint(&self) -> uint { *self as uint }
230
231     #[inline]
232     unsafe fn offset(self, count: int) -> *T { intrinsics::offset(self, count) }
233
234     #[inline]
235     unsafe fn to_option(&self) -> Option<&T> {
236         if self.is_null() {
237             None
238         } else {
239             Some(cast::transmute(*self))
240         }
241     }
242 }
243
244 impl<T> RawPtr<T> for *mut T {
245     #[inline]
246     fn null() -> *mut T { mut_null() }
247
248     #[inline]
249     fn is_null(&self) -> bool { *self == RawPtr::null() }
250
251     #[inline]
252     fn to_uint(&self) -> uint { *self as uint }
253
254     #[inline]
255     unsafe fn offset(self, count: int) -> *mut T { intrinsics::offset(self as *T, count) as *mut T }
256
257     #[inline]
258     unsafe fn to_option(&self) -> Option<&T> {
259         if self.is_null() {
260             None
261         } else {
262             Some(cast::transmute(*self))
263         }
264     }
265 }
266
267 // Equality for pointers
268 #[cfg(not(test))]
269 impl<T> Eq for *T {
270     #[inline]
271     fn eq(&self, other: &*T) -> bool {
272         *self == *other
273     }
274     #[inline]
275     fn ne(&self, other: &*T) -> bool { !self.eq(other) }
276 }
277
278 #[cfg(not(test))]
279 impl<T> Eq for *mut T {
280     #[inline]
281     fn eq(&self, other: &*mut T) -> bool {
282         *self == *other
283     }
284     #[inline]
285     fn ne(&self, other: &*mut T) -> bool { !self.eq(other) }
286 }
287
288 // Equivalence for pointers
289 #[cfg(not(test))]
290 impl<T> Equiv<*mut T> for *T {
291     fn equiv(&self, other: &*mut T) -> bool {
292         self.to_uint() == other.to_uint()
293     }
294 }
295
296 #[cfg(not(test))]
297 impl<T> Equiv<*T> for *mut T {
298     fn equiv(&self, other: &*T) -> bool {
299         self.to_uint() == other.to_uint()
300     }
301 }
302
303 // Equality for extern "C" fn pointers
304 #[cfg(not(test))]
305 mod externfnpointers {
306     use cast;
307     use cmp::Eq;
308
309     impl<_R> Eq for extern "C" fn() -> _R {
310         #[inline]
311         fn eq(&self, other: &extern "C" fn() -> _R) -> bool {
312             let self_: *() = unsafe { cast::transmute(*self) };
313             let other_: *() = unsafe { cast::transmute(*other) };
314             self_ == other_
315         }
316         #[inline]
317         fn ne(&self, other: &extern "C" fn() -> _R) -> bool {
318             !self.eq(other)
319         }
320     }
321     macro_rules! fnptreq(
322         ($($p:ident),*) => {
323             impl<_R,$($p),*> Eq for extern "C" fn($($p),*) -> _R {
324                 #[inline]
325                 fn eq(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
326                     let self_: *() = unsafe { cast::transmute(*self) };
327                     let other_: *() = unsafe { cast::transmute(*other) };
328                     self_ == other_
329                 }
330                 #[inline]
331                 fn ne(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
332                     !self.eq(other)
333                 }
334             }
335         }
336     )
337     fnptreq!(A)
338     fnptreq!(A,B)
339     fnptreq!(A,B,C)
340     fnptreq!(A,B,C,D)
341     fnptreq!(A,B,C,D,E)
342 }
343
344 // Comparison for pointers
345 #[cfg(not(test))]
346 impl<T> Ord for *T {
347     #[inline]
348     fn lt(&self, other: &*T) -> bool {
349         *self < *other
350     }
351     #[inline]
352     fn le(&self, other: &*T) -> bool {
353         *self <= *other
354     }
355     #[inline]
356     fn ge(&self, other: &*T) -> bool {
357         *self >= *other
358     }
359     #[inline]
360     fn gt(&self, other: &*T) -> bool {
361         *self > *other
362     }
363 }
364
365 #[cfg(not(test))]
366 impl<T> Ord for *mut T {
367     #[inline]
368     fn lt(&self, other: &*mut T) -> bool {
369         *self < *other
370     }
371     #[inline]
372     fn le(&self, other: &*mut T) -> bool {
373         *self <= *other
374     }
375     #[inline]
376     fn ge(&self, other: &*mut T) -> bool {
377         *self >= *other
378     }
379     #[inline]
380     fn gt(&self, other: &*mut T) -> bool {
381         *self > *other
382     }
383 }
384
385 #[cfg(test)]
386 pub mod ptr_tests {
387     use super::*;
388     use prelude::*;
389
390     use c_str::ToCStr;
391     use cast;
392     use libc;
393     use str;
394     use vec::{ImmutableVector, MutableVector};
395
396     #[test]
397     fn test() {
398         unsafe {
399             struct Pair {
400                 fst: int,
401                 snd: int
402             };
403             let mut p = Pair {fst: 10, snd: 20};
404             let pptr: *mut Pair = &mut p;
405             let iptr: *mut int = cast::transmute(pptr);
406             assert_eq!(*iptr, 10);
407             *iptr = 30;
408             assert_eq!(*iptr, 30);
409             assert_eq!(p.fst, 30);
410
411             *pptr = Pair {fst: 50, snd: 60};
412             assert_eq!(*iptr, 50);
413             assert_eq!(p.fst, 50);
414             assert_eq!(p.snd, 60);
415
416             let v0 = ~[32000u16, 32001u16, 32002u16];
417             let mut v1 = ~[0u16, 0u16, 0u16];
418
419             copy_memory(v1.as_mut_ptr().offset(1),
420                         v0.as_ptr().offset(1), 1);
421             assert!((v1[0] == 0u16 && v1[1] == 32001u16 && v1[2] == 0u16));
422             copy_memory(v1.as_mut_ptr(),
423                         v0.as_ptr().offset(2), 1);
424             assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
425                      v1[2] == 0u16));
426             copy_memory(v1.as_mut_ptr().offset(2),
427                         v0.as_ptr(), 1u);
428             assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
429                      v1[2] == 32000u16));
430         }
431     }
432
433     #[test]
434     fn test_position() {
435         use libc::c_char;
436
437         "hello".with_c_str(|p| {
438             unsafe {
439                 assert!(2u == position(p, |c| *c == 'l' as c_char));
440                 assert!(4u == position(p, |c| *c == 'o' as c_char));
441                 assert!(5u == position(p, |c| *c == 0 as c_char));
442             }
443         })
444     }
445
446     #[test]
447     fn test_buf_len() {
448         "hello".with_c_str(|p0| {
449             "there".with_c_str(|p1| {
450                 "thing".with_c_str(|p2| {
451                     let v = ~[p0, p1, p2, null()];
452                     unsafe {
453                         assert_eq!(buf_len(v.as_ptr()), 3u);
454                     }
455                 })
456             })
457         })
458     }
459
460     #[test]
461     fn test_is_null() {
462         let p: *int = null();
463         assert!(p.is_null());
464         assert!(!p.is_not_null());
465
466         let q = unsafe { p.offset(1) };
467         assert!(!q.is_null());
468         assert!(q.is_not_null());
469
470         let mp: *mut int = mut_null();
471         assert!(mp.is_null());
472         assert!(!mp.is_not_null());
473
474         let mq = unsafe { mp.offset(1) };
475         assert!(!mq.is_null());
476         assert!(mq.is_not_null());
477     }
478
479     #[test]
480     fn test_to_option() {
481         unsafe {
482             let p: *int = null();
483             assert_eq!(p.to_option(), None);
484
485             let q: *int = &2;
486             assert_eq!(q.to_option().unwrap(), &2);
487
488             let p: *mut int = mut_null();
489             assert_eq!(p.to_option(), None);
490
491             let q: *mut int = &mut 2;
492             assert_eq!(q.to_option().unwrap(), &2);
493         }
494     }
495
496     #[test]
497     fn test_ptr_addition() {
498         unsafe {
499             let xs = ~[5, ..16];
500             let mut ptr = xs.as_ptr();
501             let end = ptr.offset(16);
502
503             while ptr < end {
504                 assert_eq!(*ptr, 5);
505                 ptr = ptr.offset(1);
506             }
507
508             let mut xs_mut = xs.clone();
509             let mut m_ptr = xs_mut.as_mut_ptr();
510             let m_end = m_ptr.offset(16);
511
512             while m_ptr < m_end {
513                 *m_ptr += 5;
514                 m_ptr = m_ptr.offset(1);
515             }
516
517             assert_eq!(xs_mut, ~[10, ..16]);
518         }
519     }
520
521     #[test]
522     fn test_ptr_subtraction() {
523         unsafe {
524             let xs = ~[0,1,2,3,4,5,6,7,8,9];
525             let mut idx = 9i8;
526             let ptr = xs.as_ptr();
527
528             while idx >= 0i8 {
529                 assert_eq!(*(ptr.offset(idx as int)), idx as int);
530                 idx = idx - 1i8;
531             }
532
533             let mut xs_mut = xs.clone();
534             let m_start = xs_mut.as_mut_ptr();
535             let mut m_ptr = m_start.offset(9);
536
537             while m_ptr >= m_start {
538                 *m_ptr += *m_ptr;
539                 m_ptr = m_ptr.offset(-1);
540             }
541
542             assert_eq!(xs_mut, ~[0,2,4,6,8,10,12,14,16,18]);
543         }
544     }
545
546     #[test]
547     fn test_ptr_array_each_with_len() {
548         unsafe {
549             let one = "oneOne".to_c_str();
550             let two = "twoTwo".to_c_str();
551             let three = "threeThree".to_c_str();
552             let arr = ~[
553                 one.with_ref(|buf| buf),
554                 two.with_ref(|buf| buf),
555                 three.with_ref(|buf| buf),
556             ];
557             let expected_arr = [
558                 one, two, three
559             ];
560
561             let mut ctr = 0;
562             let mut iteration_count = 0;
563             array_each_with_len(arr.as_ptr(), arr.len(), |e| {
564                     let actual = str::raw::from_c_str(e);
565                     let expected = expected_arr[ctr].with_ref(|buf| {
566                             str::raw::from_c_str(buf)
567                         });
568                     debug!(
569                         "test_ptr_array_each_with_len e: {}, a: {}",
570                         expected, actual);
571                     assert_eq!(actual, expected);
572                     ctr += 1;
573                     iteration_count += 1;
574                 });
575             assert_eq!(iteration_count, 3u);
576         }
577     }
578
579     #[test]
580     fn test_ptr_array_each() {
581         unsafe {
582             let one = "oneOne".to_c_str();
583             let two = "twoTwo".to_c_str();
584             let three = "threeThree".to_c_str();
585             let arr = ~[
586                 one.with_ref(|buf| buf),
587                 two.with_ref(|buf| buf),
588                 three.with_ref(|buf| buf),
589                 // fake a null terminator
590                 null(),
591             ];
592             let expected_arr = [
593                 one, two, three
594             ];
595
596             let arr_ptr = arr.as_ptr();
597             let mut ctr = 0;
598             let mut iteration_count = 0;
599             array_each(arr_ptr, |e| {
600                     let actual = str::raw::from_c_str(e);
601                     let expected = expected_arr[ctr].with_ref(|buf| {
602                         str::raw::from_c_str(buf)
603                     });
604                     debug!(
605                         "test_ptr_array_each e: {}, a: {}",
606                         expected, actual);
607                     assert_eq!(actual, expected);
608                     ctr += 1;
609                     iteration_count += 1;
610                 });
611             assert_eq!(iteration_count, 3);
612         }
613     }
614
615     #[test]
616     #[should_fail]
617     fn test_ptr_array_each_with_len_null_ptr() {
618         unsafe {
619             array_each_with_len(0 as **libc::c_char, 1, |e| {
620                 str::raw::from_c_str(e);
621             });
622         }
623     }
624     #[test]
625     #[should_fail]
626     fn test_ptr_array_each_null_ptr() {
627         unsafe {
628             array_each(0 as **libc::c_char, |e| {
629                 str::raw::from_c_str(e);
630             });
631         }
632     }
633
634     #[test]
635     fn test_set_memory() {
636         let mut xs = [0u8, ..20];
637         let ptr = xs.as_mut_ptr();
638         unsafe { set_memory(ptr, 5u8, xs.len()); }
639         assert_eq!(xs, [5u8, ..20]);
640     }
641 }