]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr.rs
Rename all raw pointers as necessary
[rust.git] / src / libcore / 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 // FIXME: talk about offset, copy_memory, copy_nonoverlapping_memory
12
13 //! Operations on unsafe pointers, `*const T`, and `*mut T`.
14 //!
15 //! Working with unsafe pointers in Rust is uncommon,
16 //! typically limited to a few patterns.
17 //!
18 //! Use the [`null` function](fn.null.html) to create null pointers,
19 //! the [`is_null`](trait.RawPtr.html#tymethod.is_null)
20 //! and [`is_not_null`](trait.RawPtr.html#method.is_not_null)
21 //! methods of the [`RawPtr` trait](trait.RawPtr.html) to check for null.
22 //! The `RawPtr` trait is imported by the prelude, so `is_null` etc.
23 //! work everywhere. The `RawPtr` also defines the `offset` method,
24 //! for pointer math.
25 //!
26 //! # Common ways to create unsafe pointers
27 //!
28 //! ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
29 //!
30 //! ```
31 //! let my_num: int = 10;
32 //! let my_num_ptr: *const int = &my_num;
33 //! let mut my_speed: int = 88;
34 //! let my_speed_ptr: *mut int = &mut my_speed;
35 //! ```
36 //!
37 //! This does not take ownership of the original allocation
38 //! and requires no resource management later,
39 //! but you must not use the pointer after its lifetime.
40 //!
41 //! ## 2. Transmute an owned box (`Box<T>`).
42 //!
43 //! The `transmute` function takes, by value, whatever it's given
44 //! and returns it as whatever type is requested, as long as the
45 //! types are the same size. Because `Box<T>` and `*mut T` have the same
46 //! representation they can be trivially,
47 //! though unsafely, transformed from one type to the other.
48 //!
49 //! ```
50 //! use std::mem;
51 //!
52 //! unsafe {
53 //!     let my_num: Box<int> = box 10;
54 //!     let my_num: *const int = mem::transmute(my_num);
55 //!     let my_speed: Box<int> = box 88;
56 //!     let my_speed: *mut int = mem::transmute(my_speed);
57 //!
58 //!     // By taking ownership of the original `Box<T>` though
59 //!     // we are obligated to transmute it back later to be destroyed.
60 //!     drop(mem::transmute::<_, Box<int>>(my_speed));
61 //!     drop(mem::transmute::<_, Box<int>>(my_num));
62 //! }
63 //! ```
64 //!
65 //! Note that here the call to `drop` is for clarity - it indicates
66 //! that we are done with the given value and it should be destroyed.
67 //!
68 //! ## 3. Get it from C.
69 //!
70 //! ```
71 //! extern crate libc;
72 //!
73 //! use std::mem;
74 //!
75 //! fn main() {
76 //!     unsafe {
77 //!         let my_num: *mut int = libc::malloc(mem::size_of::<int>() as libc::size_t) as *mut int;
78 //!         if my_num.is_null() {
79 //!             fail!("failed to allocate memory");
80 //!         }
81 //!         libc::free(my_num as *mut libc::c_void);
82 //!     }
83 //! }
84 //! ```
85 //!
86 //! Usually you wouldn't literally use `malloc` and `free` from Rust,
87 //! but C APIs hand out a lot of pointers generally, so are a common source
88 //! of unsafe pointers in Rust.
89
90 use mem;
91 use clone::Clone;
92 use intrinsics;
93 use iter::{range, Iterator};
94 use option::{Some, None, Option};
95
96 #[cfg(not(test))] use cmp::{PartialEq, Eq, PartialOrd, Equiv};
97
98 /// Create a null pointer.
99 ///
100 /// # Example
101 ///
102 /// ```
103 /// use std::ptr;
104 ///
105 /// let p: *const int = ptr::null();
106 /// assert!(p.is_null());
107 /// ```
108 #[inline]
109 #[unstable = "may need a different name after pending changes to pointer types"]
110 pub fn null<T>() -> *const T { 0 as *const T }
111
112 /// Create an unsafe mutable null pointer.
113 ///
114 /// # Example
115 ///
116 /// ```
117 /// use std::ptr;
118 ///
119 /// let p: *mut int = ptr::mut_null();
120 /// assert!(p.is_null());
121 /// ```
122 #[inline]
123 #[unstable = "may need a different name after pending changes to pointer types"]
124 pub fn mut_null<T>() -> *mut T { 0 as *mut T }
125
126 /// Copies data from one location to another.
127 ///
128 /// Copies `count` elements (not bytes) from `src` to `dst`. The source
129 /// and destination may overlap.
130 ///
131 /// `copy_memory` is semantically equivalent to C's `memmove`.
132 ///
133 /// # Example
134 ///
135 /// Efficiently create a Rust vector from an unsafe buffer:
136 ///
137 /// ```
138 /// use std::ptr;
139 ///
140 /// unsafe fn from_buf_raw<T>(ptr: *const T, elts: uint) -> Vec<T> {
141 ///     let mut dst = Vec::with_capacity(elts);
142 ///     dst.set_len(elts);
143 ///     ptr::copy_memory(dst.as_mut_ptr(), ptr, elts);
144 ///     dst
145 /// }
146 /// ```
147 ///
148 #[inline]
149 #[unstable]
150 pub unsafe fn copy_memory<T>(dst: *mut T, src: *const T, count: uint) {
151     intrinsics::copy_memory(dst, src, count)
152 }
153
154 /// Copies data from one location to another.
155 ///
156 /// Copies `count` elements (not bytes) from `src` to `dst`. The source
157 /// and destination may *not* overlap.
158 ///
159 /// `copy_nonoverlapping_memory` is semantically equivalent to C's `memcpy`.
160 ///
161 /// # Example
162 ///
163 /// A safe swap function:
164 ///
165 /// ```
166 /// use std::mem;
167 /// use std::ptr;
168 ///
169 /// fn swap<T>(x: &mut T, y: &mut T) {
170 ///     unsafe {
171 ///         // Give ourselves some scratch space to work with
172 ///         let mut t: T = mem::uninitialized();
173 ///
174 ///         // Perform the swap, `&mut` pointers never alias
175 ///         ptr::copy_nonoverlapping_memory(&mut t, &*x, 1);
176 ///         ptr::copy_nonoverlapping_memory(x, &*y, 1);
177 ///         ptr::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 ///         mem::forget(t);
182 ///     }
183 /// }
184 /// ```
185 ///
186 /// # Safety Note
187 ///
188 /// If the source and destination overlap then the behavior of this
189 /// function is undefined.
190 #[inline]
191 #[unstable]
192 pub unsafe fn copy_nonoverlapping_memory<T>(dst: *mut T,
193                                             src: *const T,
194                                             count: uint) {
195     intrinsics::copy_nonoverlapping_memory(dst, src, count)
196 }
197
198 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
199 /// bytes of memory starting at `dst` to `c`.
200 #[inline]
201 #[experimental = "uncertain about naming and semantics"]
202 pub unsafe fn set_memory<T>(dst: *mut T, c: u8, count: uint) {
203     intrinsics::set_memory(dst, c, count)
204 }
205
206 /// Zeroes out `count * size_of::<T>` bytes of memory at `dst`
207 #[inline]
208 #[experimental = "uncertain about naming and semantics"]
209 #[allow(experimental)]
210 pub unsafe fn zero_memory<T>(dst: *mut T, count: uint) {
211     set_memory(dst, 0, count);
212 }
213
214 /// Swap the values at two mutable locations of the same type, without
215 /// deinitialising either. They may overlap.
216 #[inline]
217 #[unstable]
218 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
219     // Give ourselves some scratch space to work with
220     let mut tmp: T = mem::uninitialized();
221     let t: *mut T = &mut tmp;
222
223     // Perform the swap
224     copy_nonoverlapping_memory(t, &*x, 1);
225     copy_memory(x, &*y, 1); // `x` and `y` may overlap
226     copy_nonoverlapping_memory(y, &*t, 1);
227
228     // y and t now point to the same thing, but we need to completely forget `tmp`
229     // because it's no longer relevant.
230     mem::forget(tmp);
231 }
232
233 /// Replace the value at a mutable location with a new one, returning the old
234 /// value, without deinitialising either.
235 #[inline]
236 #[unstable]
237 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
238     mem::swap(mem::transmute(dest), &mut src); // cannot overlap
239     src
240 }
241
242 /// Reads the value from `*src` and returns it.
243 #[inline(always)]
244 #[unstable]
245 pub unsafe fn read<T>(src: *const T) -> T {
246     let mut tmp: T = mem::uninitialized();
247     copy_nonoverlapping_memory(&mut tmp, src, 1);
248     tmp
249 }
250
251 /// Reads the value from `*src` and nulls it out.
252 /// This currently prevents destructors from executing.
253 #[inline(always)]
254 #[experimental]
255 #[allow(experimental)]
256 pub unsafe fn read_and_zero<T>(dest: *mut T) -> T {
257     // Copy the data out from `dest`:
258     let tmp = read(&*dest);
259
260     // Now zero out `dest`:
261     zero_memory(dest, 1);
262
263     tmp
264 }
265
266 /// Unsafely overwrite a memory location with the given value without destroying
267 /// the old value.
268 ///
269 /// This operation is unsafe because it does not destroy the previous value
270 /// contained at the location `dst`. This could leak allocations or resources,
271 /// so care must be taken to previously deallocate the value at `dst`.
272 #[inline]
273 #[unstable]
274 pub unsafe fn write<T>(dst: *mut T, src: T) {
275     intrinsics::move_val_init(&mut *dst, src)
276 }
277
278 /// Given a *const *const T (pointer to an array of pointers),
279 /// iterate through each *const T, up to the provided `len`,
280 /// passing to the provided callback function
281 #[deprecated = "old-style iteration. use a loop and RawPtr::offset"]
282 pub unsafe fn array_each_with_len<T>(arr: *const *const T, len: uint,
283                                      cb: |*const T|) {
284     if arr.is_null() {
285         fail!("ptr::array_each_with_len failure: arr input is null pointer");
286     }
287     //let start_ptr = *arr;
288     for e in range(0, len) {
289         let n = arr.offset(e as int);
290         cb(*n);
291     }
292 }
293
294 /// Given a null-pointer-terminated *const *const T (pointer to
295 /// an array of pointers), iterate through each *const T,
296 /// passing to the provided callback function
297 ///
298 /// # Safety Note
299 ///
300 /// This will only work with a null-terminated
301 /// pointer array.
302 #[deprecated = "old-style iteration. use a loop and RawPtr::offset"]
303 #[allow(deprecated)]
304 pub unsafe fn array_each<T>(arr: *const  *const T, cb: |*const T|) {
305     if arr.is_null()  {
306         fail!("ptr::array_each_with_len failure: arr input is null pointer");
307     }
308     let len = buf_len(arr);
309     array_each_with_len(arr, len, cb);
310 }
311
312 /// Return the offset of the first null pointer in `buf`.
313 #[inline]
314 #[deprecated = "use a loop and RawPtr::offset"]
315 #[allow(deprecated)]
316 pub unsafe fn buf_len<T>(buf: *const *const T) -> uint {
317     position(buf, |i| *i == null())
318 }
319
320 /// Return the first offset `i` such that `f(buf[i]) == true`.
321 #[inline]
322 #[deprecated = "old-style iteration. use a loop and RawPtr::offset"]
323 pub unsafe fn position<T>(buf: *const T, f: |&T| -> bool) -> uint {
324     let mut i = 0;
325     loop {
326         if f(&(*buf.offset(i as int))) { return i; }
327         else { i += 1; }
328     }
329 }
330
331 /// Methods on raw pointers
332 pub trait RawPtr<T> {
333     /// Returns the null pointer.
334     fn null() -> Self;
335     /// Returns true if the pointer is equal to the null pointer.
336     fn is_null(&self) -> bool;
337     /// Returns true if the pointer is not equal to the null pointer.
338     fn is_not_null(&self) -> bool { !self.is_null() }
339     /// Returns the value of this pointer (ie, the address it points to)
340     fn to_uint(&self) -> uint;
341     /// Returns `None` if the pointer is null, or else returns the value wrapped
342     /// in `Some`.
343     ///
344     /// # Safety Notes
345     ///
346     /// While this method is useful for null-safety, it is important to note
347     /// that this is still an unsafe operation because the returned value could
348     /// be pointing to invalid memory.
349     unsafe fn to_option(&self) -> Option<&T>;
350     /// Calculates the offset from a pointer. The offset *must* be in-bounds of
351     /// the object, or one-byte-past-the-end.  `count` is in units of T; e.g. a
352     /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
353     unsafe fn offset(self, count: int) -> Self;
354 }
355
356 impl<T> RawPtr<T> for *const T {
357     #[inline]
358     fn null() -> *const T { null() }
359
360     #[inline]
361     fn is_null(&self) -> bool { *self == RawPtr::null() }
362
363     #[inline]
364     fn to_uint(&self) -> uint { *self as uint }
365
366     #[inline]
367     unsafe fn offset(self, count: int) -> *const T {
368         intrinsics::offset(self, count)
369     }
370
371     #[inline]
372     unsafe fn to_option(&self) -> Option<&T> {
373         if self.is_null() {
374             None
375         } else {
376             Some(&**self)
377         }
378     }
379 }
380
381 impl<T> RawPtr<T> for *mut T {
382     #[inline]
383     fn null() -> *mut T { mut_null() }
384
385     #[inline]
386     fn is_null(&self) -> bool { *self == RawPtr::null() }
387
388     #[inline]
389     fn to_uint(&self) -> uint { *self as uint }
390
391     #[inline]
392     unsafe fn offset(self, count: int) -> *mut T {
393         intrinsics::offset(self as *const T, count) as *mut T
394     }
395
396     #[inline]
397     unsafe fn to_option(&self) -> Option<&T> {
398         if self.is_null() {
399             None
400         } else {
401             Some(&**self)
402         }
403     }
404 }
405
406 // Equality for pointers
407 #[cfg(not(test))]
408 impl<T> PartialEq for *const T {
409     #[inline]
410     fn eq(&self, other: &*const T) -> bool {
411         *self == *other
412     }
413     #[inline]
414     fn ne(&self, other: &*const T) -> bool { !self.eq(other) }
415 }
416
417 #[cfg(not(test))]
418 impl<T> Eq for *const T {}
419
420 #[cfg(not(test))]
421 impl<T> PartialEq for *mut T {
422     #[inline]
423     fn eq(&self, other: &*mut T) -> bool {
424         *self == *other
425     }
426     #[inline]
427     fn ne(&self, other: &*mut T) -> bool { !self.eq(other) }
428 }
429
430 #[cfg(not(test))]
431 impl<T> Eq for *mut T {}
432
433 // Equivalence for pointers
434 #[cfg(not(test))]
435 impl<T> Equiv<*mut T> for *const T {
436     fn equiv(&self, other: &*mut T) -> bool {
437         self.to_uint() == other.to_uint()
438     }
439 }
440
441 #[cfg(not(test))]
442 impl<T> Equiv<*const T> for *mut T {
443     fn equiv(&self, other: &*const T) -> bool {
444         self.to_uint() == other.to_uint()
445     }
446 }
447
448 impl<T> Clone for *const T {
449     #[inline]
450     fn clone(&self) -> *const T {
451         *self
452     }
453 }
454
455 impl<T> Clone for *mut T {
456     #[inline]
457     fn clone(&self) -> *mut T {
458         *self
459     }
460 }
461
462 // Equality for extern "C" fn pointers
463 #[cfg(not(test))]
464 mod externfnpointers {
465     use mem;
466     use cmp::PartialEq;
467
468     impl<_R> PartialEq for extern "C" fn() -> _R {
469         #[inline]
470         fn eq(&self, other: &extern "C" fn() -> _R) -> bool {
471             let self_: *const () = unsafe { mem::transmute(*self) };
472             let other_: *const () = unsafe { mem::transmute(*other) };
473             self_ == other_
474         }
475     }
476     macro_rules! fnptreq(
477         ($($p:ident),*) => {
478             impl<_R,$($p),*> PartialEq for extern "C" fn($($p),*) -> _R {
479                 #[inline]
480                 fn eq(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
481                     let self_: *const () = unsafe { mem::transmute(*self) };
482
483                     let other_: *const () = unsafe { mem::transmute(*other) };
484                     self_ == other_
485                 }
486             }
487         }
488     )
489     fnptreq!(A)
490     fnptreq!(A,B)
491     fnptreq!(A,B,C)
492     fnptreq!(A,B,C,D)
493     fnptreq!(A,B,C,D,E)
494 }
495
496 // Comparison for pointers
497 #[cfg(not(test))]
498 impl<T> PartialOrd for *const T {
499     #[inline]
500     fn lt(&self, other: &*const T) -> bool { *self < *other }
501 }
502
503 #[cfg(not(test))]
504 impl<T> PartialOrd for *mut T {
505     #[inline]
506     fn lt(&self, other: &*mut T) -> bool { *self < *other }
507 }
508
509 #[cfg(test)]
510 #[allow(deprecated, experimental)]
511 pub mod test {
512     use super::*;
513     use prelude::*;
514
515     use realstd::c_str::ToCStr;
516     use mem;
517     use libc;
518     use realstd::str;
519     use realstd::str::Str;
520     use realstd::vec::Vec;
521     use realstd::collections::Collection;
522     use slice::{ImmutableVector, MutableVector};
523
524     #[test]
525     fn test() {
526         unsafe {
527             struct Pair {
528                 fst: int,
529                 snd: int
530             };
531             let mut p = Pair {fst: 10, snd: 20};
532             let pptr: *mut Pair = &mut p;
533             let iptr: *mut int = mem::transmute(pptr);
534             assert_eq!(*iptr, 10);
535             *iptr = 30;
536             assert_eq!(*iptr, 30);
537             assert_eq!(p.fst, 30);
538
539             *pptr = Pair {fst: 50, snd: 60};
540             assert_eq!(*iptr, 50);
541             assert_eq!(p.fst, 50);
542             assert_eq!(p.snd, 60);
543
544             let v0 = vec![32000u16, 32001u16, 32002u16];
545             let mut v1 = vec![0u16, 0u16, 0u16];
546
547             copy_memory(v1.as_mut_ptr().offset(1),
548                         v0.as_ptr().offset(1), 1);
549             assert!((*v1.get(0) == 0u16 &&
550                      *v1.get(1) == 32001u16 &&
551                      *v1.get(2) == 0u16));
552             copy_memory(v1.as_mut_ptr(),
553                         v0.as_ptr().offset(2), 1);
554             assert!((*v1.get(0) == 32002u16 &&
555                      *v1.get(1) == 32001u16 &&
556                      *v1.get(2) == 0u16));
557             copy_memory(v1.as_mut_ptr().offset(2),
558                         v0.as_ptr(), 1u);
559             assert!((*v1.get(0) == 32002u16 &&
560                      *v1.get(1) == 32001u16 &&
561                      *v1.get(2) == 32000u16));
562         }
563     }
564
565     #[test]
566     fn test_position() {
567         use libc::c_char;
568
569         "hello".with_c_str(|p| {
570             unsafe {
571                 assert!(2u == position(p, |c| *c == 'l' as c_char));
572                 assert!(4u == position(p, |c| *c == 'o' as c_char));
573                 assert!(5u == position(p, |c| *c == 0 as c_char));
574             }
575         })
576     }
577
578     #[test]
579     fn test_buf_len() {
580         "hello".with_c_str(|p0| {
581             "there".with_c_str(|p1| {
582                 "thing".with_c_str(|p2| {
583                     let v = vec![p0, p1, p2, null()];
584                     unsafe {
585                         assert_eq!(buf_len(v.as_ptr()), 3u);
586                     }
587                 })
588             })
589         })
590     }
591
592     #[test]
593     fn test_is_null() {
594         let p: *const int = null();
595         assert!(p.is_null());
596         assert!(!p.is_not_null());
597
598         let q = unsafe { p.offset(1) };
599         assert!(!q.is_null());
600         assert!(q.is_not_null());
601
602         let mp: *mut int = mut_null();
603         assert!(mp.is_null());
604         assert!(!mp.is_not_null());
605
606         let mq = unsafe { mp.offset(1) };
607         assert!(!mq.is_null());
608         assert!(mq.is_not_null());
609     }
610
611     #[test]
612     fn test_to_option() {
613         unsafe {
614             let p: *const int = null();
615             assert_eq!(p.to_option(), None);
616
617             let q: *const int = &2;
618             assert_eq!(q.to_option().unwrap(), &2);
619
620             let p: *mut int = mut_null();
621             assert_eq!(p.to_option(), None);
622
623             let q: *mut int = &mut 2;
624             assert_eq!(q.to_option().unwrap(), &2);
625         }
626     }
627
628     #[test]
629     fn test_ptr_addition() {
630         unsafe {
631             let xs = Vec::from_elem(16, 5i);
632             let mut ptr = xs.as_ptr();
633             let end = ptr.offset(16);
634
635             while ptr < end {
636                 assert_eq!(*ptr, 5);
637                 ptr = ptr.offset(1);
638             }
639
640             let mut xs_mut = xs;
641             let mut m_ptr = xs_mut.as_mut_ptr();
642             let m_end = m_ptr.offset(16);
643
644             while m_ptr < m_end {
645                 *m_ptr += 5;
646                 m_ptr = m_ptr.offset(1);
647             }
648
649             assert!(xs_mut == Vec::from_elem(16, 10i));
650         }
651     }
652
653     #[test]
654     fn test_ptr_subtraction() {
655         unsafe {
656             let xs = vec![0,1,2,3,4,5,6,7,8,9];
657             let mut idx = 9i8;
658             let ptr = xs.as_ptr();
659
660             while idx >= 0i8 {
661                 assert_eq!(*(ptr.offset(idx as int)), idx as int);
662                 idx = idx - 1i8;
663             }
664
665             let mut xs_mut = xs;
666             let m_start = xs_mut.as_mut_ptr();
667             let mut m_ptr = m_start.offset(9);
668
669             while m_ptr >= m_start {
670                 *m_ptr += *m_ptr;
671                 m_ptr = m_ptr.offset(-1);
672             }
673
674             assert!(xs_mut == vec![0,2,4,6,8,10,12,14,16,18]);
675         }
676     }
677
678     #[test]
679     fn test_ptr_array_each_with_len() {
680         unsafe {
681             let one = "oneOne".to_c_str();
682             let two = "twoTwo".to_c_str();
683             let three = "threeThree".to_c_str();
684             let arr = vec![
685                 one.with_ref(|buf| buf),
686                 two.with_ref(|buf| buf),
687                 three.with_ref(|buf| buf)
688             ];
689             let expected_arr = [
690                 one, two, three
691             ];
692
693             let mut ctr = 0;
694             let mut iteration_count = 0;
695             array_each_with_len(arr.as_ptr(), arr.len(), |e| {
696                     let actual = str::raw::from_c_str(e);
697                     let expected = expected_arr[ctr].with_ref(|buf| {
698                             str::raw::from_c_str(buf)
699                         });
700                     assert_eq!(actual.as_slice(), expected.as_slice());
701                     ctr += 1;
702                     iteration_count += 1;
703                 });
704             assert_eq!(iteration_count, 3u);
705         }
706     }
707
708     #[test]
709     fn test_ptr_array_each() {
710         unsafe {
711             let one = "oneOne".to_c_str();
712             let two = "twoTwo".to_c_str();
713             let three = "threeThree".to_c_str();
714             let arr = vec![
715                 one.with_ref(|buf| buf),
716                 two.with_ref(|buf| buf),
717                 three.with_ref(|buf| buf),
718                 // fake a null terminator
719                 null()
720             ];
721             let expected_arr = [
722                 one, two, three
723             ];
724
725             let arr_ptr = arr.as_ptr();
726             let mut ctr = 0u;
727             let mut iteration_count = 0u;
728             array_each(arr_ptr, |e| {
729                     let actual = str::raw::from_c_str(e);
730                     let expected = expected_arr[ctr].with_ref(|buf| {
731                         str::raw::from_c_str(buf)
732                     });
733                     assert_eq!(actual.as_slice(), expected.as_slice());
734                     ctr += 1;
735                     iteration_count += 1;
736                 });
737             assert_eq!(iteration_count, 3);
738         }
739     }
740
741     #[test]
742     #[should_fail]
743     fn test_ptr_array_each_with_len_null_ptr() {
744         unsafe {
745             array_each_with_len(0 as *const *const libc::c_char, 1, |e| {
746                 str::raw::from_c_str(e);
747             });
748         }
749     }
750     #[test]
751     #[should_fail]
752     fn test_ptr_array_each_null_ptr() {
753         unsafe {
754             array_each(0 as *const *const libc::c_char, |e| {
755                 str::raw::from_c_str(e);
756             });
757         }
758     }
759
760     #[test]
761     fn test_set_memory() {
762         let mut xs = [0u8, ..20];
763         let ptr = xs.as_mut_ptr();
764         unsafe { set_memory(ptr, 5u8, xs.len()); }
765         assert!(xs == [5u8, ..20]);
766     }
767 }