Skip to content

Commit 3b8a8fa

Browse files
committed
ch2: Refactor
1 parent 90ff7ba commit 3b8a8fa

File tree

1 file changed

+19
-24
lines changed

1 file changed

+19
-24
lines changed

rust/src/main.rs

Lines changed: 19 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -23,21 +23,15 @@ struct BrowserWidget {
2323
max_scroll: i32,
2424
}
2525

26-
trait Browser {
27-
fn load(&mut self, url: String);
28-
}
29-
30-
struct BrowserApplication {}
31-
32-
impl Browser for BrowserWidget {
33-
fn load(&mut self, url: String) {
34-
let (_headers, body) = request(&url);
35-
let text = lex(&body);
26+
impl BrowserWidget {
27+
fn new(text: String) -> BrowserWidget {
3628
let mut cursor_x = HSTEP;
3729
let mut cursor_y = VSTEP;
30+
let mut max_scroll = 0;
31+
let mut display_list = Vec::new();
3832
for c in text.chars() {
39-
self.max_scroll = cmp::max(self.max_scroll, cursor_y);
40-
self.display_list.push(Character {
33+
max_scroll = cmp::max(max_scroll, cursor_y);
34+
display_list.push(Character {
4135
x: cursor_x,
4236
y: cursor_y,
4337
ch: c,
@@ -48,6 +42,12 @@ impl Browser for BrowserWidget {
4842
cursor_x = HSTEP;
4943
}
5044
}
45+
BrowserWidget {
46+
display_list: display_list,
47+
scroll: 0,
48+
min_scroll: 0,
49+
max_scroll: max_scroll,
50+
}
5151
}
5252
}
5353

@@ -112,18 +112,13 @@ impl Widget<i32> for BrowserWidget {
112112
}
113113
}
114114

115+
struct BrowserApplication {}
116+
115117
impl BrowserApplication {
116-
fn run(&self, url: String) {
117-
let browser_widget = || -> BrowserWidget {
118-
let mut ret = BrowserWidget {
119-
display_list: Vec::new(),
120-
scroll: 0,
121-
min_scroll: 0,
122-
max_scroll: 0,
123-
};
124-
ret.load(url);
125-
ret
126-
};
118+
fn run(&self, url: &str) {
119+
let (_headers, body) = request(&url);
120+
let text = lex(&body);
121+
let browser_widget = || -> BrowserWidget { BrowserWidget::new(text) };
127122
let window = WindowDesc::new(browser_widget)
128123
.title(LocalizedString::new("Browser-engineering"))
129124
.window_size((WIDTH as f64, HEIGHT as f64));
@@ -137,5 +132,5 @@ impl BrowserApplication {
137132
pub fn main() {
138133
let args: Vec<String> = std::env::args().collect();
139134
let app = BrowserApplication {};
140-
app.run(args[1].clone());
135+
app.run(&args[1]);
141136
}

0 commit comments

Comments
 (0)