]> git.lizzy.rs Git - rust.git/blob - src/libstd/ptr.rs
Find the cratemap at runtime on windows.
[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 option::{Option, Some, None};
19 use unstable::intrinsics;
20 use util::swap;
21
22 #[cfg(not(test))] use cmp::{Eq, Ord};
23
24 /// Calculate the offset from a pointer
25 #[inline]
26 pub unsafe fn offset<T>(ptr: *T, count: int) -> *T {
27     intrinsics::offset(ptr, count)
28 }
29
30 /// Calculate the offset from a mut pointer. The count *must* be in bounds or
31 /// otherwise the loads of this address are undefined.
32 #[inline]
33 pub unsafe fn mut_offset<T>(ptr: *mut T, count: int) -> *mut T {
34     intrinsics::offset(ptr as *T, count) as *mut T
35 }
36
37 /// Return the offset of the first null pointer in `buf`.
38 #[inline]
39 pub unsafe fn buf_len<T>(buf: **T) -> uint {
40     position(buf, |i| *i == null())
41 }
42
43 impl<T> Clone for *T {
44     #[inline]
45     fn clone(&self) -> *T {
46         *self
47     }
48 }
49
50 /// Return the first offset `i` such that `f(buf[i]) == true`.
51 #[inline]
52 pub unsafe fn position<T>(buf: *T, f: &fn(&T) -> bool) -> uint {
53     let mut i = 0;
54     loop {
55         if f(&(*offset(buf, i as int))) { return i; }
56         else { i += 1; }
57     }
58 }
59
60 /// Create an unsafe null pointer
61 #[inline]
62 pub fn null<T>() -> *T { 0 as *T }
63
64 /// Create an unsafe mutable null pointer
65 #[inline]
66 pub fn mut_null<T>() -> *mut T { 0 as *mut T }
67
68 /// Returns true if the pointer is equal to the null pointer.
69 #[inline]
70 pub fn is_null<T,P:RawPtr<T>>(ptr: P) -> bool { ptr.is_null() }
71
72 /// Returns true if the pointer is not equal to the null pointer.
73 #[inline]
74 pub fn is_not_null<T,P:RawPtr<T>>(ptr: P) -> bool { ptr.is_not_null() }
75
76 /**
77  * Copies data from one location to another.
78  *
79  * Copies `count` elements (not bytes) from `src` to `dst`. The source
80  * and destination may overlap.
81  */
82 #[inline]
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),
87                           count as u32);
88 }
89
90 /**
91  * Copies data from one location to another.
92  *
93  * Copies `count` elements (not bytes) from `src` to `dst`. The source
94  * and destination may overlap.
95  */
96 #[inline]
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),
101                           count as u64);
102 }
103
104 /**
105  * Copies data from one location to another.
106  *
107  * Copies `count` elements (not bytes) from `src` to `dst`. The source
108  * and destination may *not* overlap.
109  */
110 #[inline]
111 #[cfg(target_word_size = "32")]
112 pub unsafe fn copy_nonoverlapping_memory<T,P:RawPtr<T>>(dst: *mut T,
113                                                         src: P,
114                                                         count: uint) {
115     intrinsics::memcpy32(dst,
116                          cast::transmute_immut_unsafe(src),
117                          count as u32);
118 }
119
120 /**
121  * Copies data from one location to another.
122  *
123  * Copies `count` elements (not bytes) from `src` to `dst`. The source
124  * and destination may *not* overlap.
125  */
126 #[inline]
127 #[cfg(target_word_size = "64")]
128 pub unsafe fn copy_nonoverlapping_memory<T,P:RawPtr<T>>(dst: *mut T,
129                                                         src: P,
130                                                         count: uint) {
131     intrinsics::memcpy64(dst,
132                          cast::transmute_immut_unsafe(src),
133                          count as u64);
134 }
135
136 /**
137  * Invokes memset on the specified pointer, setting `count * size_of::<T>()`
138  * bytes of memory starting at `dst` to `c`.
139  */
140 #[inline]
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);
144 }
145
146 /**
147  * Invokes memset on the specified pointer, setting `count * size_of::<T>()`
148  * bytes of memory starting at `dst` to `c`.
149  */
150 #[inline]
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);
154 }
155
156 /**
157  * Zeroes out `count * size_of::<T>` bytes of memory at `dst`
158  */
159 #[inline]
160 pub unsafe fn zero_memory<T>(dst: *mut T, count: uint) {
161     set_memory(dst, 0, count);
162 }
163
164 /**
165  * Swap the values at two mutable locations of the same type, without
166  * deinitialising or copying either one.
167  */
168 #[inline]
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;
173
174     // Perform the swap
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);
178
179     // y and t now point to the same thing, but we need to completely forget `tmp`
180     // because it's no longer relevant.
181     cast::forget(tmp);
182 }
183
184 /**
185  * Replace the value at a mutable location with a new one, returning the old
186  * value, without deinitialising or copying either one.
187  */
188 #[inline]
189 pub unsafe fn replace_ptr<T>(dest: *mut T, mut src: T) -> T {
190     swap(cast::transmute(dest), &mut src); // cannot overlap
191     src
192 }
193
194 /**
195  * Reads the value from `*src` and returns it. Does not copy `*src`.
196  */
197 #[inline(always)]
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);
201     tmp
202 }
203
204 /**
205  * Reads the value from `*src` and nulls it out.
206  * This currently prevents destructors from executing.
207  */
208 #[inline(always)]
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);
212
213     // Now zero out `dest`:
214     zero_memory(dest, 1);
215
216     tmp
217 }
218
219 /// Transform a region pointer - &T - to an unsafe pointer - *T.
220 #[inline]
221 pub fn to_unsafe_ptr<T>(thing: &T) -> *T {
222     thing as *T
223 }
224
225 /// Transform a mutable region pointer - &mut T - to a mutable unsafe pointer - *mut T.
226 #[inline]
227 pub fn to_mut_unsafe_ptr<T>(thing: &mut T) -> *mut T {
228     thing as *mut T
229 }
230
231 /**
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
235
236   SAFETY NOTE: Pointer-arithmetic. Dragons be here.
237 */
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");
242     }
243     //let start_ptr = *arr;
244     for e in range(0, len) {
245         let n = offset(arr, e as int);
246         cb(*n);
247     }
248     debug!("array_each_with_len: after iterate");
249 }
250
251 /**
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
255
256   SAFETY NOTE: This will only work with a null-terminated
257   pointer array. Barely less-dodgy Pointer Arithmetic.
258   Dragons be here.
259 */
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");
263     }
264     let len = buf_len(arr);
265     debug!("array_each inferred len: %u",
266                     len);
267     array_each_with_len(arr, len, cb);
268 }
269
270 #[allow(missing_doc)]
271 pub trait RawPtr<T> {
272     fn null() -> Self;
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;
278 }
279
280 /// Extension methods for immutable pointers
281 impl<T> RawPtr<T> for *T {
282     /// Returns the null pointer.
283     #[inline]
284     fn null() -> *T { null() }
285
286     /// Returns true if the pointer is equal to the null pointer.
287     #[inline]
288     fn is_null(&self) -> bool { *self == RawPtr::null() }
289
290     /// Returns true if the pointer is not equal to the null pointer.
291     #[inline]
292     fn is_not_null(&self) -> bool { *self != RawPtr::null() }
293
294     /// Returns the address of this pointer.
295     #[inline]
296     fn to_uint(&self) -> uint { *self as uint }
297
298     ///
299     /// Returns `None` if the pointer is null, or else returns the value wrapped
300     /// in `Some`.
301     ///
302     /// # Safety Notes
303     ///
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.
307     ///
308     #[inline]
309     unsafe fn to_option(&self) -> Option<&T> {
310         if self.is_null() { None } else {
311             Some(cast::transmute(*self))
312         }
313     }
314
315     /// Calculates the offset from a pointer. The offset *must* be in-bounds of
316     /// the object, or one-byte-past-the-end.
317     #[inline]
318     unsafe fn offset(self, count: int) -> *T { offset(self, count) }
319 }
320
321 /// Extension methods for mutable pointers
322 impl<T> RawPtr<T> for *mut T {
323     /// Returns the null pointer.
324     #[inline]
325     fn null() -> *mut T { mut_null() }
326
327     /// Returns true if the pointer is equal to the null pointer.
328     #[inline]
329     fn is_null(&self) -> bool { *self == RawPtr::null() }
330
331     /// Returns true if the pointer is not equal to the null pointer.
332     #[inline]
333     fn is_not_null(&self) -> bool { *self != RawPtr::null() }
334
335     /// Returns the address of this pointer.
336     #[inline]
337     fn to_uint(&self) -> uint { *self as uint }
338
339     ///
340     /// Returns `None` if the pointer is null, or else returns the value wrapped
341     /// in `Some`.
342     ///
343     /// # Safety Notes
344     ///
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.
348     ///
349     #[inline]
350     unsafe fn to_option(&self) -> Option<&T> {
351         if self.is_null() { None } else {
352             Some(cast::transmute(*self))
353         }
354     }
355
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.
359     ///
360     /// This method should be preferred over `offset` when the guarantee can be
361     /// satisfied, to enable better optimization.
362     #[inline]
363     unsafe fn offset(self, count: int) -> *mut T { mut_offset(self, count) }
364 }
365
366 // Equality for pointers
367 #[cfg(not(test))]
368 impl<T> Eq for *T {
369     #[inline]
370     fn eq(&self, other: &*T) -> bool {
371         *self == *other
372     }
373     #[inline]
374     fn ne(&self, other: &*T) -> bool { !self.eq(other) }
375 }
376
377 #[cfg(not(test))]
378 impl<T> Eq for *mut T {
379     #[inline]
380     fn eq(&self, other: &*mut T) -> bool {
381         *self == *other
382     }
383     #[inline]
384     fn ne(&self, other: &*mut T) -> bool { !self.eq(other) }
385 }
386
387 // Equivalence for pointers
388 #[cfg(not(test))]
389 impl<T> Equiv<*mut T> for *T {
390     fn equiv(&self, other: &*mut T) -> bool {
391         self.to_uint() == other.to_uint()
392     }
393 }
394
395 #[cfg(not(test))]
396 impl<T> Equiv<*T> for *mut T {
397     fn equiv(&self, other: &*T) -> bool {
398         self.to_uint() == other.to_uint()
399     }
400 }
401
402 // Equality for extern "C" fn pointers
403 #[cfg(not(test))]
404 mod externfnpointers {
405     use cast;
406     use cmp::Eq;
407
408     impl<_R> Eq for extern "C" fn() -> _R {
409         #[inline]
410         fn eq(&self, other: &extern "C" fn() -> _R) -> bool {
411             let self_: *() = unsafe { cast::transmute(*self) };
412             let other_: *() = unsafe { cast::transmute(*other) };
413             self_ == other_
414         }
415         #[inline]
416         fn ne(&self, other: &extern "C" fn() -> _R) -> bool {
417             !self.eq(other)
418         }
419     }
420     macro_rules! fnptreq(
421         ($($p:ident),*) => {
422             impl<_R,$($p),*> Eq for extern "C" fn($($p),*) -> _R {
423                 #[inline]
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) };
427                     self_ == other_
428                 }
429                 #[inline]
430                 fn ne(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
431                     !self.eq(other)
432                 }
433             }
434         }
435     )
436     fnptreq!(A)
437     fnptreq!(A,B)
438     fnptreq!(A,B,C)
439     fnptreq!(A,B,C,D)
440     fnptreq!(A,B,C,D,E)
441 }
442
443 // Comparison for pointers
444 #[cfg(not(test))]
445 impl<T> Ord for *T {
446     #[inline]
447     fn lt(&self, other: &*T) -> bool {
448         *self < *other
449     }
450     #[inline]
451     fn le(&self, other: &*T) -> bool {
452         *self <= *other
453     }
454     #[inline]
455     fn ge(&self, other: &*T) -> bool {
456         *self >= *other
457     }
458     #[inline]
459     fn gt(&self, other: &*T) -> bool {
460         *self > *other
461     }
462 }
463
464 #[cfg(not(test))]
465 impl<T> Ord for *mut T {
466     #[inline]
467     fn lt(&self, other: &*mut T) -> bool {
468         *self < *other
469     }
470     #[inline]
471     fn le(&self, other: &*mut T) -> bool {
472         *self <= *other
473     }
474     #[inline]
475     fn ge(&self, other: &*mut T) -> bool {
476         *self >= *other
477     }
478     #[inline]
479     fn gt(&self, other: &*mut T) -> bool {
480         *self > *other
481     }
482 }
483
484 #[cfg(test)]
485 pub mod ptr_tests {
486     use super::*;
487     use prelude::*;
488
489     use c_str::ToCStr;
490     use cast;
491     use libc;
492     use str;
493     use vec;
494
495     #[test]
496     fn test() {
497         unsafe {
498             struct Pair {
499                 fst: int,
500                 snd: int
501             };
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);
506             *iptr = 30;
507             assert_eq!(*iptr, 30);
508             assert_eq!(p.fst, 30);
509
510             *pptr = Pair {fst: 50, snd: 60};
511             assert_eq!(*iptr, 50);
512             assert_eq!(p.fst, 50);
513             assert_eq!(p.snd, 60);
514
515             let v0 = ~[32000u16, 32001u16, 32002u16];
516             let mut v1 = ~[0u16, 0u16, 0u16];
517
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 &&
524                      v1[2] == 0u16));
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 &&
528                      v1[2] == 32000u16));
529         }
530     }
531
532     #[test]
533     fn test_position() {
534         use libc::c_char;
535
536         do "hello".with_c_str |p| {
537             unsafe {
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));
541             }
542         }
543     }
544
545     #[test]
546     fn test_buf_len() {
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);
553                         assert_eq!(len, 4u);
554                     }
555                 }
556             }
557         }
558     }
559
560     #[test]
561     fn test_is_null() {
562         let p: *int = null();
563         assert!(p.is_null());
564         assert!(!p.is_not_null());
565
566         let q = unsafe { offset(p, 1) };
567         assert!(!q.is_null());
568         assert!(q.is_not_null());
569
570         let mp: *mut int = mut_null();
571         assert!(mp.is_null());
572         assert!(!mp.is_not_null());
573
574         let mq = unsafe { mp.offset(1) };
575         assert!(!mq.is_null());
576         assert!(mq.is_not_null());
577     }
578
579     #[test]
580     fn test_to_option() {
581         unsafe {
582             let p: *int = null();
583             assert_eq!(p.to_option(), None);
584
585             let q: *int = &2;
586             assert_eq!(q.to_option().unwrap(), &2);
587
588             let p: *mut int = mut_null();
589             assert_eq!(p.to_option(), None);
590
591             let q: *mut int = &mut 2;
592             assert_eq!(q.to_option().unwrap(), &2);
593         }
594     }
595
596     #[test]
597     fn test_ptr_addition() {
598         use vec::raw::*;
599
600         unsafe {
601             let xs = ~[5, ..16];
602             let mut ptr = to_ptr(xs);
603             let end = ptr.offset(16);
604
605             while ptr < end {
606                 assert_eq!(*ptr, 5);
607                 ptr = ptr.offset(1);
608             }
609
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);
613
614             while m_ptr < m_end {
615                 *m_ptr += 5;
616                 m_ptr = m_ptr.offset(1);
617             }
618
619             assert_eq!(xs_mut, ~[10, ..16]);
620         }
621     }
622
623     #[test]
624     fn test_ptr_subtraction() {
625         use vec::raw::*;
626
627         unsafe {
628             let xs = ~[0,1,2,3,4,5,6,7,8,9];
629             let mut idx = 9i8;
630             let ptr = to_ptr(xs);
631
632             while idx >= 0i8 {
633                 assert_eq!(*(ptr.offset(idx as int)), idx as int);
634                 idx = idx - 1i8;
635             }
636
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);
640
641             while m_ptr >= m_start {
642                 *m_ptr += *m_ptr;
643                 m_ptr = m_ptr.offset(-1);
644             }
645
646             assert_eq!(xs_mut, ~[0,2,4,6,8,10,12,14,16,18]);
647         }
648     }
649
650     #[test]
651     fn test_ptr_array_each_with_len() {
652         unsafe {
653             let one = "oneOne".to_c_str();
654             let two = "twoTwo".to_c_str();
655             let three = "threeThree".to_c_str();
656             let arr = ~[
657                 one.with_ref(|buf| buf),
658                 two.with_ref(|buf| buf),
659                 three.with_ref(|buf| buf),
660             ];
661             let expected_arr = [
662                 one, two, three
663             ];
664
665             do arr.as_imm_buf |arr_ptr, arr_len| {
666                 let mut ctr = 0;
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)
672                      };
673                      debug!(
674                          "test_ptr_array_each_with_len e: %s, a: %s",
675                          expected, actual);
676                      assert_eq!(actual, expected);
677                      ctr += 1;
678                      iteration_count += 1;
679                  }
680                 assert_eq!(iteration_count, 3u);
681             }
682         }
683     }
684
685     #[test]
686     fn test_ptr_array_each() {
687         unsafe {
688             let one = "oneOne".to_c_str();
689             let two = "twoTwo".to_c_str();
690             let three = "threeThree".to_c_str();
691             let arr = ~[
692                 one.with_ref(|buf| buf),
693                 two.with_ref(|buf| buf),
694                 three.with_ref(|buf| buf),
695                 // fake a null terminator
696                 null(),
697             ];
698             let expected_arr = [
699                 one, two, three
700             ];
701
702             do arr.as_imm_buf |arr_ptr, _| {
703                 let mut ctr = 0;
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)
709                      };
710                      debug!(
711                          "test_ptr_array_each e: %s, a: %s",
712                          expected, actual);
713                      assert_eq!(actual, expected);
714                      ctr += 1;
715                      iteration_count += 1;
716                  }
717                 assert_eq!(iteration_count, 3);
718             }
719         }
720     }
721
722     #[test]
723     #[should_fail]
724     fn test_ptr_array_each_with_len_null_ptr() {
725         unsafe {
726             array_each_with_len(0 as **libc::c_char, 1, |e| {
727                 str::raw::from_c_str(e);
728             });
729         }
730     }
731     #[test]
732     #[should_fail]
733     fn test_ptr_array_each_null_ptr() {
734         unsafe {
735             array_each(0 as **libc::c_char, |e| {
736                 str::raw::from_c_str(e);
737             });
738         }
739     }
740
741     #[test]
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]);
747     }
748 }