]> git.lizzy.rs Git - rust.git/blob - src/libstd/ptr.rs
auto merge of #12299 : sfackler/rust/limit-return, r=alexcrichton
[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 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.
217     unsafe fn offset(self, count: int) -> Self;
218 }
219
220 impl<T> RawPtr<T> for *T {
221     #[inline]
222     fn null() -> *T { null() }
223
224     #[inline]
225     fn is_null(&self) -> bool { *self == RawPtr::null() }
226
227     #[inline]
228     fn to_uint(&self) -> uint { *self as uint }
229
230     #[inline]
231     unsafe fn offset(self, count: int) -> *T { intrinsics::offset(self, count) }
232
233     #[inline]
234     unsafe fn to_option(&self) -> Option<&T> {
235         if self.is_null() {
236             None
237         } else {
238             Some(cast::transmute(*self))
239         }
240     }
241 }
242
243 impl<T> RawPtr<T> for *mut T {
244     #[inline]
245     fn null() -> *mut T { mut_null() }
246
247     #[inline]
248     fn is_null(&self) -> bool { *self == RawPtr::null() }
249
250     #[inline]
251     fn to_uint(&self) -> uint { *self as uint }
252
253     #[inline]
254     unsafe fn offset(self, count: int) -> *mut T { intrinsics::offset(self as *T, count) as *mut T }
255
256     #[inline]
257     unsafe fn to_option(&self) -> Option<&T> {
258         if self.is_null() {
259             None
260         } else {
261             Some(cast::transmute(*self))
262         }
263     }
264 }
265
266 // Equality for pointers
267 #[cfg(not(test))]
268 impl<T> Eq for *T {
269     #[inline]
270     fn eq(&self, other: &*T) -> bool {
271         *self == *other
272     }
273     #[inline]
274     fn ne(&self, other: &*T) -> bool { !self.eq(other) }
275 }
276
277 #[cfg(not(test))]
278 impl<T> Eq for *mut T {
279     #[inline]
280     fn eq(&self, other: &*mut T) -> bool {
281         *self == *other
282     }
283     #[inline]
284     fn ne(&self, other: &*mut T) -> bool { !self.eq(other) }
285 }
286
287 // Equivalence for pointers
288 #[cfg(not(test))]
289 impl<T> Equiv<*mut T> for *T {
290     fn equiv(&self, other: &*mut T) -> bool {
291         self.to_uint() == other.to_uint()
292     }
293 }
294
295 #[cfg(not(test))]
296 impl<T> Equiv<*T> for *mut T {
297     fn equiv(&self, other: &*T) -> bool {
298         self.to_uint() == other.to_uint()
299     }
300 }
301
302 // Equality for extern "C" fn pointers
303 #[cfg(not(test))]
304 mod externfnpointers {
305     use cast;
306     use cmp::Eq;
307
308     impl<_R> Eq for extern "C" fn() -> _R {
309         #[inline]
310         fn eq(&self, other: &extern "C" fn() -> _R) -> bool {
311             let self_: *() = unsafe { cast::transmute(*self) };
312             let other_: *() = unsafe { cast::transmute(*other) };
313             self_ == other_
314         }
315         #[inline]
316         fn ne(&self, other: &extern "C" fn() -> _R) -> bool {
317             !self.eq(other)
318         }
319     }
320     macro_rules! fnptreq(
321         ($($p:ident),*) => {
322             impl<_R,$($p),*> Eq for extern "C" fn($($p),*) -> _R {
323                 #[inline]
324                 fn eq(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
325                     let self_: *() = unsafe { cast::transmute(*self) };
326                     let other_: *() = unsafe { cast::transmute(*other) };
327                     self_ == other_
328                 }
329                 #[inline]
330                 fn ne(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
331                     !self.eq(other)
332                 }
333             }
334         }
335     )
336     fnptreq!(A)
337     fnptreq!(A,B)
338     fnptreq!(A,B,C)
339     fnptreq!(A,B,C,D)
340     fnptreq!(A,B,C,D,E)
341 }
342
343 // Comparison for pointers
344 #[cfg(not(test))]
345 impl<T> Ord for *T {
346     #[inline]
347     fn lt(&self, other: &*T) -> bool {
348         *self < *other
349     }
350     #[inline]
351     fn le(&self, other: &*T) -> bool {
352         *self <= *other
353     }
354     #[inline]
355     fn ge(&self, other: &*T) -> bool {
356         *self >= *other
357     }
358     #[inline]
359     fn gt(&self, other: &*T) -> bool {
360         *self > *other
361     }
362 }
363
364 #[cfg(not(test))]
365 impl<T> Ord for *mut T {
366     #[inline]
367     fn lt(&self, other: &*mut T) -> bool {
368         *self < *other
369     }
370     #[inline]
371     fn le(&self, other: &*mut T) -> bool {
372         *self <= *other
373     }
374     #[inline]
375     fn ge(&self, other: &*mut T) -> bool {
376         *self >= *other
377     }
378     #[inline]
379     fn gt(&self, other: &*mut T) -> bool {
380         *self > *other
381     }
382 }
383
384 #[cfg(test)]
385 pub mod ptr_tests {
386     use super::*;
387     use prelude::*;
388
389     use c_str::ToCStr;
390     use cast;
391     use libc;
392     use str;
393     use vec::{ImmutableVector, MutableVector};
394
395     #[test]
396     fn test() {
397         unsafe {
398             struct Pair {
399                 fst: int,
400                 snd: int
401             };
402             let mut p = Pair {fst: 10, snd: 20};
403             let pptr: *mut Pair = &mut p;
404             let iptr: *mut int = cast::transmute(pptr);
405             assert_eq!(*iptr, 10);
406             *iptr = 30;
407             assert_eq!(*iptr, 30);
408             assert_eq!(p.fst, 30);
409
410             *pptr = Pair {fst: 50, snd: 60};
411             assert_eq!(*iptr, 50);
412             assert_eq!(p.fst, 50);
413             assert_eq!(p.snd, 60);
414
415             let v0 = ~[32000u16, 32001u16, 32002u16];
416             let mut v1 = ~[0u16, 0u16, 0u16];
417
418             copy_memory(v1.as_mut_ptr().offset(1),
419                         v0.as_ptr().offset(1), 1);
420             assert!((v1[0] == 0u16 && v1[1] == 32001u16 && v1[2] == 0u16));
421             copy_memory(v1.as_mut_ptr(),
422                         v0.as_ptr().offset(2), 1);
423             assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
424                      v1[2] == 0u16));
425             copy_memory(v1.as_mut_ptr().offset(2),
426                         v0.as_ptr(), 1u);
427             assert!((v1[0] == 32002u16 && v1[1] == 32001u16 &&
428                      v1[2] == 32000u16));
429         }
430     }
431
432     #[test]
433     fn test_position() {
434         use libc::c_char;
435
436         "hello".with_c_str(|p| {
437             unsafe {
438                 assert!(2u == position(p, |c| *c == 'l' as c_char));
439                 assert!(4u == position(p, |c| *c == 'o' as c_char));
440                 assert!(5u == position(p, |c| *c == 0 as c_char));
441             }
442         })
443     }
444
445     #[test]
446     fn test_buf_len() {
447         "hello".with_c_str(|p0| {
448             "there".with_c_str(|p1| {
449                 "thing".with_c_str(|p2| {
450                     let v = ~[p0, p1, p2, null()];
451                     unsafe {
452                         assert_eq!(buf_len(v.as_ptr()), 3u);
453                     }
454                 })
455             })
456         })
457     }
458
459     #[test]
460     fn test_is_null() {
461         let p: *int = null();
462         assert!(p.is_null());
463         assert!(!p.is_not_null());
464
465         let q = unsafe { p.offset(1) };
466         assert!(!q.is_null());
467         assert!(q.is_not_null());
468
469         let mp: *mut int = mut_null();
470         assert!(mp.is_null());
471         assert!(!mp.is_not_null());
472
473         let mq = unsafe { mp.offset(1) };
474         assert!(!mq.is_null());
475         assert!(mq.is_not_null());
476     }
477
478     #[test]
479     fn test_to_option() {
480         unsafe {
481             let p: *int = null();
482             assert_eq!(p.to_option(), None);
483
484             let q: *int = &2;
485             assert_eq!(q.to_option().unwrap(), &2);
486
487             let p: *mut int = mut_null();
488             assert_eq!(p.to_option(), None);
489
490             let q: *mut int = &mut 2;
491             assert_eq!(q.to_option().unwrap(), &2);
492         }
493     }
494
495     #[test]
496     fn test_ptr_addition() {
497         unsafe {
498             let xs = ~[5, ..16];
499             let mut ptr = xs.as_ptr();
500             let end = ptr.offset(16);
501
502             while ptr < end {
503                 assert_eq!(*ptr, 5);
504                 ptr = ptr.offset(1);
505             }
506
507             let mut xs_mut = xs.clone();
508             let mut m_ptr = xs_mut.as_mut_ptr();
509             let m_end = m_ptr.offset(16);
510
511             while m_ptr < m_end {
512                 *m_ptr += 5;
513                 m_ptr = m_ptr.offset(1);
514             }
515
516             assert_eq!(xs_mut, ~[10, ..16]);
517         }
518     }
519
520     #[test]
521     fn test_ptr_subtraction() {
522         unsafe {
523             let xs = ~[0,1,2,3,4,5,6,7,8,9];
524             let mut idx = 9i8;
525             let ptr = xs.as_ptr();
526
527             while idx >= 0i8 {
528                 assert_eq!(*(ptr.offset(idx as int)), idx as int);
529                 idx = idx - 1i8;
530             }
531
532             let mut xs_mut = xs.clone();
533             let m_start = xs_mut.as_mut_ptr();
534             let mut m_ptr = m_start.offset(9);
535
536             while m_ptr >= m_start {
537                 *m_ptr += *m_ptr;
538                 m_ptr = m_ptr.offset(-1);
539             }
540
541             assert_eq!(xs_mut, ~[0,2,4,6,8,10,12,14,16,18]);
542         }
543     }
544
545     #[test]
546     fn test_ptr_array_each_with_len() {
547         unsafe {
548             let one = "oneOne".to_c_str();
549             let two = "twoTwo".to_c_str();
550             let three = "threeThree".to_c_str();
551             let arr = ~[
552                 one.with_ref(|buf| buf),
553                 two.with_ref(|buf| buf),
554                 three.with_ref(|buf| buf),
555             ];
556             let expected_arr = [
557                 one, two, three
558             ];
559
560             let mut ctr = 0;
561             let mut iteration_count = 0;
562             array_each_with_len(arr.as_ptr(), arr.len(), |e| {
563                     let actual = str::raw::from_c_str(e);
564                     let expected = expected_arr[ctr].with_ref(|buf| {
565                             str::raw::from_c_str(buf)
566                         });
567                     debug!(
568                         "test_ptr_array_each_with_len e: {}, a: {}",
569                         expected, actual);
570                     assert_eq!(actual, expected);
571                     ctr += 1;
572                     iteration_count += 1;
573                 });
574             assert_eq!(iteration_count, 3u);
575         }
576     }
577
578     #[test]
579     fn test_ptr_array_each() {
580         unsafe {
581             let one = "oneOne".to_c_str();
582             let two = "twoTwo".to_c_str();
583             let three = "threeThree".to_c_str();
584             let arr = ~[
585                 one.with_ref(|buf| buf),
586                 two.with_ref(|buf| buf),
587                 three.with_ref(|buf| buf),
588                 // fake a null terminator
589                 null(),
590             ];
591             let expected_arr = [
592                 one, two, three
593             ];
594
595             let arr_ptr = arr.as_ptr();
596             let mut ctr = 0;
597             let mut iteration_count = 0;
598             array_each(arr_ptr, |e| {
599                     let actual = str::raw::from_c_str(e);
600                     let expected = expected_arr[ctr].with_ref(|buf| {
601                         str::raw::from_c_str(buf)
602                     });
603                     debug!(
604                         "test_ptr_array_each e: {}, a: {}",
605                         expected, actual);
606                     assert_eq!(actual, expected);
607                     ctr += 1;
608                     iteration_count += 1;
609                 });
610             assert_eq!(iteration_count, 3);
611         }
612     }
613
614     #[test]
615     #[should_fail]
616     fn test_ptr_array_each_with_len_null_ptr() {
617         unsafe {
618             array_each_with_len(0 as **libc::c_char, 1, |e| {
619                 str::raw::from_c_str(e);
620             });
621         }
622     }
623     #[test]
624     #[should_fail]
625     fn test_ptr_array_each_null_ptr() {
626         unsafe {
627             array_each(0 as **libc::c_char, |e| {
628                 str::raw::from_c_str(e);
629             });
630         }
631     }
632
633     #[test]
634     fn test_set_memory() {
635         let mut xs = [0u8, ..20];
636         let ptr = xs.as_mut_ptr();
637         unsafe { set_memory(ptr, 5u8, xs.len()); }
638         assert_eq!(xs, [5u8, ..20]);
639     }
640 }