1 // Copyright 2012 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.
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.
11 //! Library to interface with chunks of memory allocated in C.
13 //! It is often desirable to safely interface with memory allocated from C,
14 //! encapsulating the unsafety into allocation and destruction time. Indeed,
15 //! allocating memory externally is currently the only way to give Rust shared
16 //! mut state with C programs that keep their own references; vectors are
17 //! unsuitable because they could be reallocated or moved at any time, and
18 //! importing C memory into a vector takes a one-time snapshot of the memory.
20 //! This module simplifies the usage of such external blocks of memory. Memory
21 //! is encapsulated into an opaque object after creation; the lifecycle of the
22 //! memory can be optionally managed by Rust, if an appropriate destructor
23 //! closure is provided. Safety is ensured by bounds-checking accesses, which
24 //! are marshalled through get and set functions.
26 //! There are three unsafe functions: the two constructors, and the
27 //! unwrap method. The constructors are unsafe for the
28 //! obvious reason (they act on a pointer that cannot be checked inside the
29 //! method), but `unwrap()` is somewhat more subtle in its unsafety.
30 //! It returns the contained pointer, but at the same time destroys the CVec
31 //! without running its destructor. This can be used to pass memory back to
32 //! C, but care must be taken that the ownership of underlying resources are
33 //! handled correctly, i.e. that allocated memory is eventually freed
40 use ops::{Drop, FnOnce};
42 use option::Option::{Some, None};
49 /// The type representing a foreign chunk of memory
57 impl<T> Drop for CVec<T> {
59 match self.dtor.take() {
61 Some(f) => f.invoke(())
67 /// Create a `CVec` from a raw pointer to a buffer with a given length.
69 /// Panics if the given pointer is null. The returned vector will not attempt
70 /// to deallocate the vector when dropped.
74 /// * base - A raw pointer to a buffer
75 /// * len - The number of elements in the buffer
76 pub unsafe fn new(base: *mut T, len: uint) -> CVec<T> {
77 assert!(base != ptr::null_mut());
85 /// Create a `CVec` from a foreign buffer, with a given length,
86 /// and a function to run upon destruction.
88 /// Panics if the given pointer is null.
92 /// * base - A foreign pointer to a buffer
93 /// * len - The number of elements in the buffer
94 /// * dtor - A fn to run when the value is destructed, useful
95 /// for freeing the buffer, etc.
96 pub unsafe fn new_with_dtor<F>(base: *mut T,
100 where F : FnOnce(), F : Send
102 assert!(base != ptr::null_mut());
103 let dtor: Thunk = Thunk::new(dtor);
111 /// View the stored data as a mutable slice.
112 pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
114 mem::transmute(raw::Slice { data: self.base as *const T, len: self.len })
118 /// Retrieves an element at a given index, returning `None` if the requested
119 /// index is greater than the length of the vector.
120 pub fn get<'a>(&'a self, ofs: uint) -> Option<&'a T> {
122 Some(unsafe { &*self.base.offset(ofs as int) })
128 /// Retrieves a mutable element at a given index, returning `None` if the
129 /// requested index is greater than the length of the vector.
130 pub fn get_mut<'a>(&'a mut self, ofs: uint) -> Option<&'a mut T> {
132 Some(unsafe { &mut *self.base.offset(ofs as int) })
138 /// Unwrap the pointer without running the destructor
140 /// This method retrieves the underlying pointer, and in the process
141 /// destroys the CVec but without running the destructor. A use case
142 /// would be transferring ownership of the buffer to a C function, as
143 /// in this case you would not want to run the destructor.
145 /// Note that if you want to access the underlying pointer without
146 /// cancelling the destructor, you can simply call `transmute` on the return
147 /// value of `get(0)`.
148 pub unsafe fn into_inner(mut self) -> *mut T {
153 /// Deprecated, use into_inner() instead
154 #[deprecated = "renamed to into_inner()"]
155 pub unsafe fn unwrap(self) -> *mut T { self.into_inner() }
157 /// Returns the number of items in this vector.
158 pub fn len(&self) -> uint { self.len }
160 /// Returns whether this vector is empty.
161 pub fn is_empty(&self) -> bool { self.len() == 0 }
164 impl<T> AsSlice<T> for CVec<T> {
165 /// View the stored data as a slice.
166 fn as_slice<'a>(&'a self) -> &'a [T] {
168 mem::transmute(raw::Slice { data: self.base as *const T, len: self.len })
181 fn malloc(n: uint) -> CVec<u8> {
183 let mem = ptr::Unique(libc::malloc(n as libc::size_t));
184 if mem.0.is_null() { ::alloc::oom() }
186 CVec::new_with_dtor(mem.0 as *mut u8,
188 move|| { libc::free(mem.0 as *mut libc::c_void); })
194 let mut cv = malloc(16);
196 *cv.get_mut(3).unwrap() = 8;
197 *cv.get_mut(4).unwrap() = 9;
198 assert_eq!(*cv.get(3).unwrap(), 8);
199 assert_eq!(*cv.get(4).unwrap(), 9);
200 assert_eq!(cv.len(), 16);
205 fn test_panic_at_null() {
207 CVec::new(ptr::null_mut::<u8>(), 9);
212 fn test_overrun_get() {
215 assert!(cv.get(17).is_none());
219 fn test_overrun_set() {
220 let mut cv = malloc(16);
222 assert!(cv.get_mut(17).is_none());
228 let cv = CVec::new_with_dtor(1 as *mut int,
230 move|:| panic!("Don't run this destructor!"));
231 let p = cv.into_inner();
232 assert_eq!(p, 1 as *mut int);