]> git.proxmox.com Git - rustc.git/blob - src/test/run-pass/specialization/specialization-default-methods.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / test / run-pass / specialization / specialization-default-methods.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(specialization)]
12
13 // Test that default methods are cascaded correctly
14
15 // First, test only use of explicit `default` items:
16
17 trait Foo {
18 fn foo(&self) -> bool;
19 }
20
21 // Specialization tree for Foo:
22 //
23 // T
24 // / \
25 // i32 i64
26
27 impl<T> Foo for T {
28 default fn foo(&self) -> bool { false }
29 }
30
31 impl Foo for i32 {}
32
33 impl Foo for i64 {
34 fn foo(&self) -> bool { true }
35 }
36
37 fn test_foo() {
38 assert!(!0i8.foo());
39 assert!(!0i32.foo());
40 assert!(0i64.foo());
41 }
42
43 // Next, test mixture of explicit `default` and provided methods:
44
45 trait Bar {
46 fn bar(&self) -> i32 { 0 }
47 }
48
49 // Specialization tree for Bar.
50 // Uses of $ designate that method is provided
51 //
52 // $Bar (the trait)
53 // |
54 // T
55 // /|\
56 // / | \
57 // / | \
58 // / | \
59 // / | \
60 // / | \
61 // $i32 &str $Vec<T>
62 // /\
63 // / \
64 // Vec<i32> $Vec<i64>
65
66 // use the provided method
67 impl<T> Bar for T {}
68
69 impl Bar for i32 {
70 fn bar(&self) -> i32 { 1 }
71 }
72 impl<'a> Bar for &'a str {}
73
74 impl<T> Bar for Vec<T> {
75 default fn bar(&self) -> i32 { 2 }
76 }
77 impl Bar for Vec<i32> {}
78 impl Bar for Vec<i64> {
79 fn bar(&self) -> i32 { 3 }
80 }
81
82 fn test_bar() {
83 assert!(0u8.bar() == 0);
84 assert!(0i32.bar() == 1);
85 assert!("hello".bar() == 0);
86 assert!(vec![()].bar() == 2);
87 assert!(vec![0i32].bar() == 2);
88 assert!(vec![0i64].bar() == 3);
89 }
90
91 fn main() {
92 test_foo();
93 test_bar();
94 }