1 // Copyright 2014 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 // As noted by this file name, this file should not exist. This file should not
12 // exist because it performs allocations which libcore is not allowed to do. The
13 // reason for this file's existence is that the `~[T]` type is a language-
14 // defined type. Traits are defined in libcore, such as `Clone`, which these
15 // types need to implement, but the implementation can only be found in
18 // Plan of attack for solving this problem:
21 // 2. Make `Box<T>` not a language feature
22 // 3. Move `Box<T>` to a separate crate, liballoc.
23 // 4. Implement relevant traits in liballoc, not libcore
25 // Currently, no progress has been made on this list.
28 use container::Container;
29 use finally::try_finally;
31 use iter::{range, Iterator};
33 use num::{CheckedMul, CheckedAdd};
34 use option::{Some, None};
38 use slice::ImmutableVector;
42 fn rust_allocate(size: uint, align: uint) -> *u8;
43 fn rust_deallocate(ptr: *u8, size: uint, align: uint);
46 unsafe fn alloc(cap: uint) -> *mut Vec<()> {
47 let cap = cap.checked_add(&mem::size_of::<Vec<()>>()).unwrap();
48 // this should use the real alignment, but the new representation will take care of that
49 let ret = rust_allocate(cap, 8) as *mut Vec<()>;
60 impl<A: Clone> Clone for ~[A] {
62 fn clone(&self) -> ~[A] {
64 let data_size = len.checked_mul(&mem::size_of::<A>()).unwrap();
65 let size = mem::size_of::<Vec<()>>().checked_add(&data_size).unwrap();
68 let ret = alloc(size) as *mut Vec<A>;
70 let a_size = mem::size_of::<A>();
71 let a_size = if a_size == 0 {1} else {a_size};
72 (*ret).fill = len * a_size;
73 (*ret).alloc = len * a_size;
76 let p = &mut (*ret).data as *mut _ as *mut A;
79 |i, ()| while *i < len {
81 &mut(*p.offset(*i as int)),
82 self.unsafe_ref(*i).clone());
86 // we must be failing, clean up after ourselves
87 for j in range(0, *i as int) {
88 ptr::read(&*p.offset(j));
90 rust_deallocate(ret as *u8, 0, 8);