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