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