]> git.proxmox.com Git - rustc.git/blob - src/test/run-pass/mir/mir_coercions.rs
New upstream version 1.31.0~beta.4+dfsg1
[rustc.git] / src / test / run-pass / mir / mir_coercions.rs
1 // Copyright 2015 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 // run-pass
12 #![feature(coerce_unsized, unsize)]
13
14 use std::ops::CoerceUnsized;
15 use std::marker::Unsize;
16
17 fn identity_coercion(x: &(Fn(u32)->u32 + Send)) -> &Fn(u32)->u32 {
18 x
19 }
20 fn fn_coercions(f: &fn(u32) -> u32) ->
21 (unsafe fn(u32) -> u32,
22 &(Fn(u32) -> u32+Send))
23 {
24 (*f, f)
25 }
26
27 fn simple_array_coercion(x: &[u8; 3]) -> &[u8] { x }
28
29 fn square(a: u32) -> u32 { a * a }
30
31 #[derive(PartialEq,Eq)]
32 struct PtrWrapper<'a, T: 'a+?Sized>(u32, u32, (), &'a T);
33 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized>
34 CoerceUnsized<PtrWrapper<'a, U>> for PtrWrapper<'a, T> {}
35
36 struct TrivPtrWrapper<'a, T: 'a+?Sized>(&'a T);
37 impl<'a, T: ?Sized+Unsize<U>, U: ?Sized>
38 CoerceUnsized<TrivPtrWrapper<'a, U>> for TrivPtrWrapper<'a, T> {}
39
40 fn coerce_ptr_wrapper(p: PtrWrapper<[u8; 3]>) -> PtrWrapper<[u8]> {
41 p
42 }
43
44 fn coerce_triv_ptr_wrapper(p: TrivPtrWrapper<[u8; 3]>) -> TrivPtrWrapper<[u8]> {
45 p
46 }
47
48 fn coerce_fat_ptr_wrapper(p: PtrWrapper<Fn(u32) -> u32+Send>)
49 -> PtrWrapper<Fn(u32) -> u32> {
50 p
51 }
52
53 fn coerce_ptr_wrapper_poly<'a, T, Trait: ?Sized>(p: PtrWrapper<'a, T>)
54 -> PtrWrapper<'a, Trait>
55 where PtrWrapper<'a, T>: CoerceUnsized<PtrWrapper<'a, Trait>>
56 {
57 p
58 }
59
60 fn main() {
61 let a = [0,1,2];
62 let square_local : fn(u32) -> u32 = square;
63 let (f,g) = fn_coercions(&square_local);
64 assert_eq!(f as usize, square as usize);
65 assert_eq!(g(4), 16);
66 assert_eq!(identity_coercion(g)(5), 25);
67
68 assert_eq!(simple_array_coercion(&a), &a);
69 let w = coerce_ptr_wrapper(PtrWrapper(2,3,(),&a));
70 assert!(w == PtrWrapper(2,3,(),&a) as PtrWrapper<[u8]>);
71
72 let w = coerce_triv_ptr_wrapper(TrivPtrWrapper(&a));
73 assert_eq!(&w.0, &a);
74
75 let z = coerce_fat_ptr_wrapper(PtrWrapper(2,3,(),&square_local));
76 assert_eq!((z.3)(6), 36);
77
78 let z: PtrWrapper<Fn(u32) -> u32> =
79 coerce_ptr_wrapper_poly(PtrWrapper(2,3,(),&square_local));
80 assert_eq!((z.3)(6), 36);
81 }