diff --git a/src/test/run-pass/placement-box-emplace-back.rs b/src/test/run-pass/placement-box-emplace-back.rs new file mode 100644 index 0000000000000..d2ce863227db2 --- /dev/null +++ b/src/test/run-pass/placement-box-emplace-back.rs @@ -0,0 +1,86 @@ +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// This test illustrates use of `box () ` syntax to +// initialize into the end of a Vec. + +#![feature(unsafe_destructor)] + +use std::cell::{UnsafeCell}; +use std::ops::{Placer,PlacementAgent}; + +struct EmplaceBack<'a, T:'a> { + vec: &'a mut Vec, +} + +pub fn main() { + let mut v : Vec<[f32, ..4]> = vec![]; + v.push([10., 20., 30., 40.]); + v.push([11., 21., 31., 41.]); + let mut pv = EmplaceBack { vec: &mut v }; + let () = box (pv) [12., 22., 32., 42.]; + let v = pv.vec; + assert!(same_contents( + v.as_slice(), + [[10., 20., 30., 40.], + [11., 21., 31., 41.], + [12., 22., 32., 42.], + ])); +} + +fn same_contents(a: &[[T, ..4]], b: &[[T, ..4]]) -> bool { + assert_eq!(a.len(), b.len()); + let len = a.len(); + for i in range(0, len) { + if a[i].as_slice() != b[i].as_slice() { + return false; + } + } + return true; +} + +struct EmplaceBackAgent { + vec_ptr: *mut Vec, + offset: uint, +} + +impl<'a, T> Placer> for EmplaceBack<'a, T> { + fn make_place(&self) -> EmplaceBackAgent { + let len = self.vec.len(); + let v = self.vec as *mut Vec; + unsafe { + (*v).reserve_additional(1); + } + EmplaceBackAgent { vec_ptr: v, offset: len } + } +} + +impl PlacementAgent for EmplaceBackAgent { + unsafe fn pointer(&self) -> *mut T { + assert_eq!((*self.vec_ptr).len(), self.offset); + assert!(self.offset < (*self.vec_ptr).capacity()); + (*self.vec_ptr).as_mut_ptr().offset(self.offset.to_int().unwrap()) + } + + unsafe fn finalize(self) -> () { + assert_eq!((*self.vec_ptr).len(), self.offset); + assert!(self.offset < (*self.vec_ptr).capacity()); + (*self.vec_ptr).set_len(self.offset + 1); + } +} + +#[unsafe_destructor] +impl Drop for EmplaceBackAgent { + fn drop(&mut self) { + // Do not need to do anything; all `make_place` did was ensure + // we had some space reserved, it did not touch the state of + // the vector itself. + } +}