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