]> git.proxmox.com Git - rustc.git/blob - src/liballoc/boxed_test.rs
Imported Upstream version 1.3.0+dfsg1
[rustc.git] / src / liballoc / boxed_test.rs
1 // Copyright 2012-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 //! Test for `boxed` mod.
12
13 use core::any::Any;
14 use core::ops::Deref;
15 use core::result::Result::{Ok, Err};
16 use core::clone::Clone;
17
18 use std::boxed;
19 use std::boxed::Box;
20
21 #[test]
22 fn test_owned_clone() {
23 let a = Box::new(5);
24 let b: Box<i32> = a.clone();
25 assert!(a == b);
26 }
27
28 #[derive(PartialEq, Eq)]
29 struct Test;
30
31 #[test]
32 fn any_move() {
33 let a = Box::new(8) as Box<Any>;
34 let b = Box::new(Test) as Box<Any>;
35
36 match a.downcast::<i32>() {
37 Ok(a) => { assert!(a == Box::new(8)); }
38 Err(..) => panic!()
39 }
40 match b.downcast::<Test>() {
41 Ok(a) => { assert!(a == Box::new(Test)); }
42 Err(..) => panic!()
43 }
44
45 let a = Box::new(8) as Box<Any>;
46 let b = Box::new(Test) as Box<Any>;
47
48 assert!(a.downcast::<Box<Test>>().is_err());
49 assert!(b.downcast::<Box<i32>>().is_err());
50 }
51
52 #[test]
53 fn test_show() {
54 let a = Box::new(8) as Box<Any>;
55 let b = Box::new(Test) as Box<Any>;
56 let a_str = format!("{:?}", a);
57 let b_str = format!("{:?}", b);
58 assert_eq!(a_str, "Any");
59 assert_eq!(b_str, "Any");
60
61 static EIGHT: usize = 8;
62 static TEST: Test = Test;
63 let a = &EIGHT as &Any;
64 let b = &TEST as &Any;
65 let s = format!("{:?}", a);
66 assert_eq!(s, "Any");
67 let s = format!("{:?}", b);
68 assert_eq!(s, "Any");
69 }
70
71 #[test]
72 fn deref() {
73 fn homura<T: Deref<Target=i32>>(_: T) { }
74 homura(Box::new(765));
75 }
76
77 #[test]
78 fn raw_sized() {
79 let x = Box::new(17);
80 let p = Box::into_raw(x);
81 unsafe {
82 assert_eq!(17, *p);
83 *p = 19;
84 let y = Box::from_raw(p);
85 assert_eq!(19, *y);
86 }
87 }
88
89 #[test]
90 fn raw_trait() {
91 trait Foo {
92 fn get(&self) -> u32;
93 fn set(&mut self, value: u32);
94 }
95
96 struct Bar(u32);
97
98 impl Foo for Bar {
99 fn get(&self) -> u32 {
100 self.0
101 }
102
103 fn set(&mut self, value: u32) {
104 self.0 = value;
105 }
106 }
107
108 let x: Box<Foo> = Box::new(Bar(17));
109 let p = Box::into_raw(x);
110 unsafe {
111 assert_eq!(17, (*p).get());
112 (*p).set(19);
113 let y: Box<Foo> = Box::from_raw(p);
114 assert_eq!(19, y.get());
115 }
116 }