]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/unsized3.rs
de5e356f8cd5b57439c6d792ac68b71802198b9c
[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, core)]
15
16 use std::mem;
17 use std::raw;
18 use std::slice;
19
20 struct Foo<T> {
21     f: [T],
22 }
23
24 struct Bar {
25     f1: usize,
26     f2: [usize],
27 }
28
29 struct Baz {
30     f1: usize,
31     f2: str,
32 }
33
34 trait Tr {
35     fn foo(&self) -> usize;
36 }
37
38 struct St {
39     f: usize
40 }
41
42 impl Tr for St {
43     fn foo(&self) -> usize {
44         self.f
45     }
46 }
47
48 struct Qux<'a> {
49     f: Tr+'a
50 }
51
52 pub fn main() {
53     let _: &Foo<f64>;
54     let _: &Bar;
55     let _: &Baz;
56
57     let _: Box<Foo<i32>>;
58     let _: Box<Bar>;
59     let _: Box<Baz>;
60
61     let _ = mem::size_of::<Box<Foo<u8>>>();
62     let _ = mem::size_of::<Box<Bar>>();
63     let _ = mem::size_of::<Box<Baz>>();
64
65     unsafe {
66         struct Foo_<T> {
67             f: [T; 3]
68         }
69
70         let data: Box<Foo_<i32>> = box Foo_{f: [1, 2, 3] };
71         let x: &Foo<i32> = mem::transmute(slice::from_raw_parts(&*data, 3));
72         assert!(x.f.len() == 3);
73         assert!(x.f[0] == 1);
74
75         struct Baz_ {
76             f1: usize,
77             f2: [u8; 5],
78         }
79
80         let data: Box<_> = box Baz_ {
81             f1: 42, f2: ['a' as u8, 'b' as u8, 'c' as u8, 'd' as u8, 'e' as u8] };
82         let x: &Baz = mem::transmute(slice::from_raw_parts(&*data, 5));
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<_> = 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 }