1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-03-30 09:22:38 +02:00

Main - Fix bug in exercise solution ()

* Fix bug in the exercise solution

Window may be nested, so its width should also consider border size.
This commit is contained in:
jaewan-github 2023-04-21 01:04:33 +09:00 committed by GitHub
parent 3cbd652698
commit e371fd7e54
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -70,6 +70,13 @@ impl Window {
fn add_widget(&mut self, widget: Box<dyn Widget>) {
self.widgets.push(widget);
}
fn inner_width(&self) -> usize {
std::cmp::max(
self.title.chars().count(),
self.widgets.iter().map(|w| w.width()).max().unwrap_or(0),
)
}
}
// ANCHOR_END: setup
@ -78,10 +85,8 @@ impl Window {
impl Widget for Window {
fn width(&self) -> usize {
// ANCHOR_END: Window-width
std::cmp::max(
self.title.chars().count(),
self.widgets.iter().map(|w| w.width()).max().unwrap_or(0),
)
// Add 4 paddings for borders
self.inner_width() + 4
}
// ANCHOR: Window-draw_into
@ -92,18 +97,18 @@ impl Widget for Window {
widget.draw_into(&mut inner);
}
let window_width = self.width();
let inner_width = self.inner_width();
// TODO: after learning about error handling, you can change
// draw_into to return Result<(), std::fmt::Error>. Then use
// the ?-operator here instead of .unwrap().
writeln!(buffer, "+-{:-<window_width$}-+", "").unwrap();
writeln!(buffer, "| {:^window_width$} |", &self.title).unwrap();
writeln!(buffer, "+={:=<window_width$}=+", "").unwrap();
writeln!(buffer, "+-{:-<inner_width$}-+", "").unwrap();
writeln!(buffer, "| {:^inner_width$} |", &self.title).unwrap();
writeln!(buffer, "+={:=<inner_width$}=+", "").unwrap();
for line in inner.lines() {
writeln!(buffer, "| {:window_width$} |", line).unwrap();
writeln!(buffer, "| {:inner_width$} |", line).unwrap();
}
writeln!(buffer, "+-{:-<window_width$}-+", "").unwrap();
writeln!(buffer, "+-{:-<inner_width$}-+", "").unwrap();
}
}