]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/unsized3.rs
fallout: run-pass tests that use box. (many could be ported to `Box::new` instead...
[rust.git] / src / test / run-pass / unsized3.rs
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.
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 // Test structs with always-unsized fields.
12
13 #![allow(unknown_features)]
14 #![feature(box_syntax)]
15
16 use std::mem;
17 use std::raw;
18
19 struct Foo<T> {
20     f: [T],
21 }
22
23 struct Bar {
24     f1: uint,
25     f2: [uint],
26 }
27
28 struct Baz {
29     f1: uint,
30     f2: str,
31 }
32
33 trait Tr {
34     fn foo(&self) -> uint;
35 }
36
37 struct St {
38     f: uint
39 }
40
41 impl Tr for St {
42     fn foo(&self) -> uint {
43         self.f
44     }
45 }
46
47 struct Qux<'a> {
48     f: Tr+'a
49 }
50
51 pub fn main() {
52     let _: &Foo<f64>;
53     let _: &Bar;
54     let _: &Baz;
55
56     let _: Box<Foo<i32>>;
57     let _: Box<Bar>;
58     let _: Box<Baz>;
59
60     let _ = mem::size_of::<Box<Foo<u8>>>();
61     let _ = mem::size_of::<Box<Bar>>();
62     let _ = mem::size_of::<Box<Baz>>();
63
64     unsafe {
65         struct Foo_<T> {
66             f: [T; 3]
67         }
68
69         let data = box Foo_{f: [1i32, 2, 3] };
70         let x: &Foo<i32> = mem::transmute(raw::Slice { len: 3, data: &*data });
71         assert!(x.f.len() == 3);
72         assert!(x.f[0] == 1);
73         assert!(x.f[1] == 2);
74         assert!(x.f[2] == 3);
75
76         struct Baz_ {
77             f1: uint,
78             f2: [u8; 5],
79         }
80
81         let data = box Baz_{ f1: 42, f2: ['a' as u8, 'b' as u8, 'c' as u8, 'd' as u8, 'e' as u8] };
82         let x: &Baz = mem::transmute( raw::Slice { len: 5, data: &*data } );
83         assert!(x.f1 == 42);
84         let chs: Vec<char> = x.f2.chars().collect();
85         assert!(chs.len() == 5);
86         assert!(chs[0] == 'a');
87         assert!(chs[1] == 'b');
88         assert!(chs[2] == 'c');
89         assert!(chs[3] == 'd');
90         assert!(chs[4] == 'e');
91
92         struct Qux_ {
93             f: St
94         }
95
96         let obj: Box<St> = box St { f: 42 };
97         let obj: &Tr = &*obj;
98         let obj: raw::TraitObject = mem::transmute(&*obj);
99         let data = box Qux_{ f: St { f: 234 } };
100         let x: &Qux = mem::transmute(raw::TraitObject { vtable: obj.vtable,
101                                                         data: mem::transmute(&*data) });
102         assert!(x.f.foo() == 234);
103     }
104 }