]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/issue-3563-3.rs
doc: remove incomplete sentence
[rust.git] / src / test / run-pass / issue-3563-3.rs
1 // Copyright 2012 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 // ASCII art shape renderer.
12 // Demonstrates traits, impls, operator overloading, non-copyable struct, unit testing.
13 // To run execute: rustc --test shapes.rs && ./shapes
14
15 // Rust's std library is tightly bound to the language itself so it is automatically linked in.
16 // However the extra library is designed to be optional (for code that must run on constrained
17 //  environments like embedded devices or special environments like kernel code) so it must
18 // be explicitly linked in.
19
20 // Extern mod controls linkage. Use controls the visibility of names to modules that are
21 // already linked in. Using WriterUtil allows us to use the write_line method.
22
23 use std::slice;
24 use std::fmt;
25
26 // Represents a position on a canvas.
27 struct Point {
28     x: int,
29     y: int,
30 }
31
32 impl Copy for Point {}
33
34 // Represents an offset on a canvas. (This has the same structure as a Point.
35 // but different semantics).
36 struct Size {
37     width: int,
38     height: int,
39 }
40
41 impl Copy for Size {}
42
43 struct Rect {
44     top_left: Point,
45     size: Size,
46 }
47
48 impl Copy for Rect {}
49
50 // Contains the information needed to do shape rendering via ASCII art.
51 struct AsciiArt {
52     width: uint,
53     height: uint,
54     fill: char,
55     lines: Vec<Vec<char> > ,
56
57     // This struct can be quite large so we'll disable copying: developers need
58     // to either pass these structs around via references or move them.
59 }
60
61 impl Drop for AsciiArt {
62     fn drop(&mut self) {}
63 }
64
65 // It's common to define a constructor sort of function to create struct instances.
66 // If there is a canonical constructor it is typically named the same as the type.
67 // Other constructor sort of functions are typically named from_foo, from_bar, etc.
68 fn AsciiArt(width: uint, height: uint, fill: char) -> AsciiArt {
69     // Use an anonymous function to build a vector of vectors containing
70     // blank characters for each position in our canvas.
71     let mut lines = Vec::new();
72     for _ in range(0, height) {
73         lines.push(Vec::from_elem(width, '.'));
74     }
75
76     // Rust code often returns values by omitting the trailing semi-colon
77     // instead of using an explicit return statement.
78     AsciiArt {width: width, height: height, fill: fill, lines: lines}
79 }
80
81 // Methods particular to the AsciiArt struct.
82 impl AsciiArt {
83     fn add_pt(&mut self, x: int, y: int) {
84         if x >= 0 && x < self.width as int {
85             if y >= 0 && y < self.height as int {
86                 // Note that numeric types don't implicitly convert to each other.
87                 let v = y as uint;
88                 let h = x as uint;
89
90                 // Vector subscripting will normally copy the element, but &v[i]
91                 // will return a reference which is what we need because the
92                 // element is:
93                 // 1) potentially large
94                 // 2) needs to be modified
95                 let row = &mut self.lines[v];
96                 row[h] = self.fill;
97             }
98         }
99     }
100 }
101
102 // Allows AsciiArt to be converted to a string using the libcore ToString trait.
103 // Note that the %s fmt! specifier will not call this automatically.
104 impl fmt::Show for AsciiArt {
105     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
106         // Convert each line into a string.
107         let lines = self.lines.iter()
108                               .map(|line| String::from_chars(line.as_slice()))
109                               .collect::<Vec<String>>();
110
111         // Concatenate the lines together using a new-line.
112         write!(f, "{}", lines.connect("\n"))
113     }
114 }
115
116 // This is similar to an interface in other languages: it defines a protocol which
117 // developers can implement for arbitrary concrete types.
118 trait Canvas {
119     fn add_point(&mut self, shape: Point);
120     fn add_rect(&mut self, shape: Rect);
121
122     // Unlike interfaces traits support default implementations.
123     // Got an ICE as soon as I added this method.
124     fn add_points(&mut self, shapes: &[Point]) {
125         for pt in shapes.iter() {self.add_point(*pt)};
126     }
127 }
128
129 // Here we provide an implementation of the Canvas methods for AsciiArt.
130 // Other implementations could also be provided (e.g. for PDF or Apple's Quartz)
131 // and code can use them polymorphically via the Canvas trait.
132 impl Canvas for AsciiArt {
133     fn add_point(&mut self, shape: Point) {
134         self.add_pt(shape.x, shape.y);
135     }
136
137     fn add_rect(&mut self, shape: Rect) {
138         // Add the top and bottom lines.
139         for x in range(shape.top_left.x, shape.top_left.x + shape.size.width) {
140             self.add_pt(x, shape.top_left.y);
141             self.add_pt(x, shape.top_left.y + shape.size.height - 1);
142         }
143
144         // Add the left and right lines.
145         for y in range(shape.top_left.y, shape.top_left.y + shape.size.height) {
146             self.add_pt(shape.top_left.x, y);
147             self.add_pt(shape.top_left.x + shape.size.width - 1, y);
148         }
149     }
150 }
151
152 // Rust's unit testing framework is currently a bit under-developed so we'll use
153 // this little helper.
154 pub fn check_strs(actual: &str, expected: &str) -> bool {
155     if actual != expected {
156         println!("Found:\n{}\nbut expected\n{}", actual, expected);
157         return false;
158     }
159     return true;
160 }
161
162
163 fn test_ascii_art_ctor() {
164     let art = AsciiArt(3, 3, '*');
165     assert!(check_strs(art.to_string().as_slice(), "...\n...\n..."));
166 }
167
168
169 fn test_add_pt() {
170     let mut art = AsciiArt(3, 3, '*');
171     art.add_pt(0, 0);
172     art.add_pt(0, -10);
173     art.add_pt(1, 2);
174     assert!(check_strs(art.to_string().as_slice(), "*..\n...\n.*."));
175 }
176
177
178 fn test_shapes() {
179     let mut art = AsciiArt(4, 4, '*');
180     art.add_rect(Rect {top_left: Point {x: 0, y: 0}, size: Size {width: 4, height: 4}});
181     art.add_point(Point {x: 2, y: 2});
182     assert!(check_strs(art.to_string().as_slice(), "****\n*..*\n*.**\n****"));
183 }
184
185 pub fn main() {
186     test_ascii_art_ctor();
187     test_add_pt();
188     test_shapes();
189 }