From 21303f21672de1405135bb785497c30150644078 Mon Sep 17 00:00:00 2001 From: BlakStar Date: Thu, 21 Sep 2023 07:56:32 +0900 Subject: [PATCH] fix(rect): prevent overflow in inner() and area() (#523) --- src/layout.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/layout.rs b/src/layout.rs index b290cdde..b3400ce8 100644 --- a/src/layout.rs +++ b/src/layout.rs @@ -206,7 +206,7 @@ impl Rect { } pub const fn area(self) -> u16 { - self.width * self.height + self.width.saturating_mul(self.height) } pub const fn left(self) -> u16 { @@ -226,14 +226,17 @@ impl Rect { } pub fn inner(self, margin: &Margin) -> Rect { - if self.width < 2 * margin.horizontal || self.height < 2 * margin.vertical { + let doubled_margin_horizontal = margin.horizontal.saturating_mul(2); + let doubled_margin_vertical = margin.vertical.saturating_mul(2); + + if self.width < doubled_margin_horizontal || self.height < doubled_margin_vertical { Rect::default() } else { Rect { - x: self.x + margin.horizontal, - y: self.y + margin.vertical, - width: self.width - 2 * margin.horizontal, - height: self.height - 2 * margin.vertical, + x: self.x.saturating_add(margin.horizontal), + y: self.y.saturating_add(margin.vertical), + width: self.width.saturating_sub(doubled_margin_horizontal), + height: self.height.saturating_sub(doubled_margin_vertical), } } }