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