]> git.lizzy.rs Git - rust.git/blob - src/libstd/ptr.rs
auto merge of #12207 : alexcrichton/rust/up-llvm, r=sfackler
[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 unstable::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 or copying either one.
106  */
107 #[inline]
108 pub unsafe fn swap_ptr<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 or copying either one.
126  */
127 #[inline]
128 pub unsafe fn replace_ptr<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. Does not copy `*src`.
135  */
136 #[inline(always)]
137 pub unsafe fn read_ptr<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_ptr<T>(dest: *mut T) -> T {
149     // Copy the data out from `dest`:
150     let tmp = read_ptr(&*dest);
151
152     // Now zero out `dest`:
153     zero_memory(dest, 1);
154
155     tmp
156 }
157
158 /// Transform a region pointer - &T - to an unsafe pointer - *T.
159 #[inline]
160 pub fn to_unsafe_ptr<T>(thing: &T) -> *T {
161     thing as *T
162 }
163
164 /// Transform a mutable region pointer - &mut T - to a mutable unsafe pointer - *mut T.
165 #[inline]
166 pub fn to_mut_unsafe_ptr<T>(thing: &mut T) -> *mut T {
167     thing as *mut T
168 }
169
170 /**
171   Given a **T (pointer to an array of pointers),
172   iterate through each *T, up to the provided `len`,
173   passing to the provided callback function
174
175   SAFETY NOTE: Pointer-arithmetic. Dragons be here.
176 */
177 pub unsafe fn array_each_with_len<T>(arr: **T, len: uint, cb: |*T|) {
178     debug!("array_each_with_len: before iterate");
179     if arr as uint == 0 {
180         fail!("ptr::array_each_with_len failure: arr input is null pointer");
181     }
182     //let start_ptr = *arr;
183     for e in range(0, len) {
184         let n = arr.offset(e as int);
185         cb(*n);
186     }
187     debug!("array_each_with_len: after iterate");
188 }
189
190 /**
191   Given a null-pointer-terminated **T (pointer to
192   an array of pointers), iterate through each *T,
193   passing to the provided callback function
194
195   SAFETY NOTE: This will only work with a null-terminated
196   pointer array. Barely less-dodgy Pointer Arithmetic.
197   Dragons be here.
198 */
199 pub unsafe fn array_each<T>(arr: **T, cb: |*T|) {
200     if arr as uint == 0 {
201         fail!("ptr::array_each_with_len failure: arr input is null pointer");
202     }
203     let len = buf_len(arr);
204     debug!("array_each inferred len: {}", len);
205     array_each_with_len(arr, len, cb);
206 }
207
208 #[allow(missing_doc)]
209 pub trait RawPtr<T> {
210     fn null() -> Self;
211     fn is_null(&self) -> bool;
212     fn is_not_null(&self) -> bool;
213     fn to_uint(&self) -> uint;
214     unsafe fn to_option(&self) -> Option<&T>;
215     unsafe fn offset(self, count: int) -> Self;
216 }
217
218 /// Extension methods for immutable pointers
219 impl<T> RawPtr<T> for *T {
220     /// Returns the null pointer.
221     #[inline]
222     fn null() -> *T { null() }
223
224     /// Returns true if the pointer is equal to the null pointer.
225     #[inline]
226     fn is_null(&self) -> bool { *self == RawPtr::null() }
227
228     /// Returns true if the pointer is not equal to the null pointer.
229     #[inline]
230     fn is_not_null(&self) -> bool { *self != RawPtr::null() }
231
232     /// Returns the address of this pointer.
233     #[inline]
234     fn to_uint(&self) -> uint { *self as uint }
235
236     ///
237     /// Returns `None` if the pointer is null, or else returns the value wrapped
238     /// in `Some`.
239     ///
240     /// # Safety Notes
241     ///
242     /// While this method is useful for null-safety, it is important to note
243     /// that this is still an unsafe operation because the returned value could
244     /// be pointing to invalid memory.
245     ///
246     #[inline]
247     unsafe fn to_option(&self) -> Option<&T> {
248         if self.is_null() { None } else {
249             Some(cast::transmute(*self))
250         }
251     }
252
253     /// Calculates the offset from a pointer. The offset *must* be in-bounds of
254     /// the object, or one-byte-past-the-end.
255     #[inline]
256     unsafe fn offset(self, count: int) -> *T { intrinsics::offset(self, count) }
257 }
258
259 /// Extension methods for mutable pointers
260 impl<T> RawPtr<T> for *mut T {
261     /// Returns the null pointer.
262     #[inline]
263     fn null() -> *mut T { mut_null() }
264
265     /// Returns true if the pointer is equal to the null pointer.
266     #[inline]
267     fn is_null(&self) -> bool { *self == RawPtr::null() }
268
269     /// Returns true if the pointer is not equal to the null pointer.
270     #[inline]
271     fn is_not_null(&self) -> bool { *self != RawPtr::null() }
272
273     /// Returns the address of this pointer.
274     #[inline]
275     fn to_uint(&self) -> uint { *self as uint }
276
277     ///
278     /// Returns `None` if the pointer is null, or else returns the value wrapped
279     /// in `Some`.
280     ///
281     /// # Safety Notes
282     ///
283     /// While this method is useful for null-safety, it is important to note
284     /// that this is still an unsafe operation because the returned value could
285     /// be pointing to invalid memory.
286     ///
287     #[inline]
288     unsafe fn to_option(&self) -> Option<&T> {
289         if self.is_null() { None } else {
290             Some(cast::transmute(*self))
291         }
292     }
293
294     /// Calculates the offset from a pointer. The offset *must* be in-bounds of
295     /// the object, or one-byte-past-the-end. An arithmetic overflow is also
296     /// undefined behaviour.
297     ///
298     /// This method should be preferred over `offset` when the guarantee can be
299     /// satisfied, to enable better optimization.
300     #[inline]
301     unsafe fn offset(self, count: int) -> *mut T { intrinsics::offset(self as *T, count) as *mut T }
302 }
303
304 // Equality for pointers
305 #[cfg(not(test))]
306 impl<T> Eq for *T {
307     #[inline]
308     fn eq(&self, other: &*T) -> bool {
309         *self == *other
310     }
311     #[inline]
312     fn ne(&self, other: &*T) -> bool { !self.eq(other) }
313 }
314
315 #[cfg(not(test))]
316 impl<T> Eq for *mut T {
317     #[inline]
318     fn eq(&self, other: &*mut T) -> bool {
319         *self == *other
320     }
321     #[inline]
322     fn ne(&self, other: &*mut T) -> bool { !self.eq(other) }
323 }
324
325 // Equivalence for pointers
326 #[cfg(not(test))]
327 impl<T> Equiv<*mut T> for *T {
328     fn equiv(&self, other: &*mut T) -> bool {
329         self.to_uint() == other.to_uint()
330     }
331 }
332
333 #[cfg(not(test))]
334 impl<T> Equiv<*T> for *mut T {
335     fn equiv(&self, other: &*T) -> bool {
336         self.to_uint() == other.to_uint()
337     }
338 }
339
340 // Equality for extern "C" fn pointers
341 #[cfg(not(test))]
342 mod externfnpointers {
343     use cast;
344     use cmp::Eq;
345
346     impl<_R> Eq for extern "C" fn() -> _R {
347         #[inline]
348         fn eq(&self, other: &extern "C" fn() -> _R) -> bool {
349             let self_: *() = unsafe { cast::transmute(*self) };
350             let other_: *() = unsafe { cast::transmute(*other) };
351             self_ == other_
352         }
353         #[inline]
354         fn ne(&self, other: &extern "C" fn() -> _R) -> bool {
355             !self.eq(other)
356         }
357     }
358     macro_rules! fnptreq(
359         ($($p:ident),*) => {
360             impl<_R,$($p),*> Eq for extern "C" fn($($p),*) -> _R {
361                 #[inline]
362                 fn eq(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
363                     let self_: *() = unsafe { cast::transmute(*self) };
364                     let other_: *() = unsafe { cast::transmute(*other) };
365                     self_ == other_
366                 }
367                 #[inline]
368                 fn ne(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
369                     !self.eq(other)
370                 }
371             }
372         }
373     )
374     fnptreq!(A)
375     fnptreq!(A,B)
376     fnptreq!(A,B,C)
377     fnptreq!(A,B,C,D)
378     fnptreq!(A,B,C,D,E)
379 }
380
381 // Comparison for pointers
382 #[cfg(not(test))]
383 impl<T> Ord for *T {
384     #[inline]
385     fn lt(&self, other: &*T) -> bool {
386         *self < *other
387     }
388     #[inline]
389     fn le(&self, other: &*T) -> bool {
390         *self <= *other
391     }
392     #[inline]
393     fn ge(&self, other: &*T) -> bool {
394         *self >= *other
395     }
396     #[inline]
397     fn gt(&self, other: &*T) -> bool {
398         *self > *other
399     }
400 }
401
402 #[cfg(not(test))]
403 impl<T> Ord for *mut T {
404     #[inline]
405     fn lt(&self, other: &*mut T) -> bool {
406         *self < *other
407     }
408     #[inline]
409     fn le(&self, other: &*mut T) -> bool {
410         *self <= *other
411     }
412     #[inline]
413     fn ge(&self, other: &*mut T) -> bool {
414         *self >= *other
415     }
416     #[inline]
417     fn gt(&self, other: &*mut T) -> bool {
418         *self > *other
419     }
420 }
421
422 #[cfg(test)]
423 pub mod ptr_tests {
424     use super::*;
425     use prelude::*;
426
427     use c_str::ToCStr;
428     use cast;
429     use libc;
430     use str;
431     use vec::{ImmutableVector, MutableVector};
432
433     #[test]
434     fn test() {
435         unsafe {
436             struct Pair {
437                 fst: int,
438                 snd: int
439             };
440             let mut p = Pair {fst: 10, snd: 20};
441             let pptr: *mut Pair = &mut p;
442             let iptr: *mut int = cast::transmute(pptr);
443             assert_eq!(*iptr, 10);
444             *iptr = 30;
445             assert_eq!(*iptr, 30);
446             assert_eq!(p.fst, 30);
447
448             *pptr = Pair {fst: 50, snd: 60};
449             assert_eq!(*iptr, 50);
450             assert_eq!(p.fst, 50);
451             assert_eq!(p.snd, 60);
452
453             let v0 = ~[32000u16, 32001u16, 32002u16];
454             let mut v1 = ~[0u16, 0u16, 0u16];
455
456             copy_memory(v1.as_mut_ptr().offset(1),
457                         v0.as_ptr().offset(1), 1);
458             assert!((v1[0] == 0u16 && v1[1] == 32001u16 && v1[2] == 0u16));
459             copy_memory(v1.as_mut_ptr(),
460                         v0.as_ptr().offset(2), 1);
461             assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
462                      v1[2] == 0u16));
463             copy_memory(v1.as_mut_ptr().offset(2),
464                         v0.as_ptr(), 1u);
465             assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
466                      v1[2] == 32000u16));
467         }
468     }
469
470     #[test]
471     fn test_position() {
472         use libc::c_char;
473
474         "hello".with_c_str(|p| {
475             unsafe {
476                 assert!(2u == position(p, |c| *c == 'l' as c_char));
477                 assert!(4u == position(p, |c| *c == 'o' as c_char));
478                 assert!(5u == position(p, |c| *c == 0 as c_char));
479             }
480         })
481     }
482
483     #[test]
484     fn test_buf_len() {
485         "hello".with_c_str(|p0| {
486             "there".with_c_str(|p1| {
487                 "thing".with_c_str(|p2| {
488                     let v = ~[p0, p1, p2, null()];
489                     unsafe {
490                         assert_eq!(buf_len(v.as_ptr()), 3u);
491                     }
492                 })
493             })
494         })
495     }
496
497     #[test]
498     fn test_is_null() {
499         let p: *int = null();
500         assert!(p.is_null());
501         assert!(!p.is_not_null());
502
503         let q = unsafe { p.offset(1) };
504         assert!(!q.is_null());
505         assert!(q.is_not_null());
506
507         let mp: *mut int = mut_null();
508         assert!(mp.is_null());
509         assert!(!mp.is_not_null());
510
511         let mq = unsafe { mp.offset(1) };
512         assert!(!mq.is_null());
513         assert!(mq.is_not_null());
514     }
515
516     #[test]
517     fn test_to_option() {
518         unsafe {
519             let p: *int = null();
520             assert_eq!(p.to_option(), None);
521
522             let q: *int = &2;
523             assert_eq!(q.to_option().unwrap(), &2);
524
525             let p: *mut int = mut_null();
526             assert_eq!(p.to_option(), None);
527
528             let q: *mut int = &mut 2;
529             assert_eq!(q.to_option().unwrap(), &2);
530         }
531     }
532
533     #[test]
534     fn test_ptr_addition() {
535         unsafe {
536             let xs = ~[5, ..16];
537             let mut ptr = xs.as_ptr();
538             let end = ptr.offset(16);
539
540             while ptr < end {
541                 assert_eq!(*ptr, 5);
542                 ptr = ptr.offset(1);
543             }
544
545             let mut xs_mut = xs.clone();
546             let mut m_ptr = xs_mut.as_mut_ptr();
547             let m_end = m_ptr.offset(16);
548
549             while m_ptr < m_end {
550                 *m_ptr += 5;
551                 m_ptr = m_ptr.offset(1);
552             }
553
554             assert_eq!(xs_mut, ~[10, ..16]);
555         }
556     }
557
558     #[test]
559     fn test_ptr_subtraction() {
560         unsafe {
561             let xs = ~[0,1,2,3,4,5,6,7,8,9];
562             let mut idx = 9i8;
563             let ptr = xs.as_ptr();
564
565             while idx >= 0i8 {
566                 assert_eq!(*(ptr.offset(idx as int)), idx as int);
567                 idx = idx - 1i8;
568             }
569
570             let mut xs_mut = xs.clone();
571             let m_start = xs_mut.as_mut_ptr();
572             let mut m_ptr = m_start.offset(9);
573
574             while m_ptr >= m_start {
575                 *m_ptr += *m_ptr;
576                 m_ptr = m_ptr.offset(-1);
577             }
578
579             assert_eq!(xs_mut, ~[0,2,4,6,8,10,12,14,16,18]);
580         }
581     }
582
583     #[test]
584     fn test_ptr_array_each_with_len() {
585         unsafe {
586             let one = "oneOne".to_c_str();
587             let two = "twoTwo".to_c_str();
588             let three = "threeThree".to_c_str();
589             let arr = ~[
590                 one.with_ref(|buf| buf),
591                 two.with_ref(|buf| buf),
592                 three.with_ref(|buf| buf),
593             ];
594             let expected_arr = [
595                 one, two, three
596             ];
597
598             let mut ctr = 0;
599             let mut iteration_count = 0;
600             array_each_with_len(arr.as_ptr(), arr.len(), |e| {
601                     let actual = str::raw::from_c_str(e);
602                     let expected = expected_arr[ctr].with_ref(|buf| {
603                             str::raw::from_c_str(buf)
604                         });
605                     debug!(
606                         "test_ptr_array_each_with_len e: {}, a: {}",
607                         expected, actual);
608                     assert_eq!(actual, expected);
609                     ctr += 1;
610                     iteration_count += 1;
611                 });
612             assert_eq!(iteration_count, 3u);
613         }
614     }
615
616     #[test]
617     fn test_ptr_array_each() {
618         unsafe {
619             let one = "oneOne".to_c_str();
620             let two = "twoTwo".to_c_str();
621             let three = "threeThree".to_c_str();
622             let arr = ~[
623                 one.with_ref(|buf| buf),
624                 two.with_ref(|buf| buf),
625                 three.with_ref(|buf| buf),
626                 // fake a null terminator
627                 null(),
628             ];
629             let expected_arr = [
630                 one, two, three
631             ];
632
633             let arr_ptr = arr.as_ptr();
634             let mut ctr = 0;
635             let mut iteration_count = 0;
636             array_each(arr_ptr, |e| {
637                     let actual = str::raw::from_c_str(e);
638                     let expected = expected_arr[ctr].with_ref(|buf| {
639                         str::raw::from_c_str(buf)
640                     });
641                     debug!(
642                         "test_ptr_array_each e: {}, a: {}",
643                         expected, actual);
644                     assert_eq!(actual, expected);
645                     ctr += 1;
646                     iteration_count += 1;
647                 });
648             assert_eq!(iteration_count, 3);
649         }
650     }
651
652     #[test]
653     #[should_fail]
654     fn test_ptr_array_each_with_len_null_ptr() {
655         unsafe {
656             array_each_with_len(0 as **libc::c_char, 1, |e| {
657                 str::raw::from_c_str(e);
658             });
659         }
660     }
661     #[test]
662     #[should_fail]
663     fn test_ptr_array_each_null_ptr() {
664         unsafe {
665             array_each(0 as **libc::c_char, |e| {
666                 str::raw::from_c_str(e);
667             });
668         }
669     }
670
671     #[test]
672     fn test_set_memory() {
673         let mut xs = [0u8, ..20];
674         let ptr = xs.as_mut_ptr();
675         unsafe { set_memory(ptr, 5u8, xs.len()); }
676         assert_eq!(xs, [5u8, ..20]);
677     }
678 }