Skip to content

Commit

Permalink
geometry: make Rectangle.grow and Rectangle.shrink return a new one
Browse files Browse the repository at this point in the history
  • Loading branch information
arrufat committed Dec 12, 2024
1 parent cf7ce1c commit ecfefd7
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions src/geometry.zig
Original file line number Diff line number Diff line change
Expand Up @@ -100,19 +100,23 @@ pub fn Rectangle(comptime T: type) type {
}

/// Grows the given rectangle by expaning its borders by `amount`.
pub fn grow(self: *Self, amount: T) void {
self.l -|= amount;
self.t -|= amount;
self.r += amount;
self.b += amount;
pub fn grow(self: Self, amount: T) Self {
return .{
.l = self.l -| amount,
.t = self.t -| amount,
.r = self.r + amount,
.b = self.b + amount,
};
}

/// Shrinks the given rectangle by shrinking its borders by `amount`.
pub fn shrink(self: *Self, amount: T) void {
self.l += amount;
self.t += amount;
self.r -|= amount;
self.b -|= amount;
pub fn shrink(self: Self, amount: T) Self {
return .{
.l = self.l + amount,
.t = self.t + amount,
.r = self.r -| amount,
.b = self.b -| amount,
};
}
};
}
Expand All @@ -131,13 +135,12 @@ test "Rectangle" {

test "Rectangle grow and shrink" {
const rect = Rectangle(i32){ .l = 50, .t = 25, .r = 100, .b = 100 };
var rect2 = rect;
const amount: i32 = 10;
rect2.grow(amount);
var rect2 = rect.grow(amount);
try expectEqual(rect.width() + 2 * amount, rect2.width());
try expectEqual(rect.height() + 2 * amount, rect2.height());
try expectEqualDeep(rect2, Rectangle(i32){ .l = 40, .t = 15, .r = 110, .b = 110 });
rect2.shrink(10);
rect2 = rect2.shrink(10);
try expectEqualDeep(rect, rect2);
}

Expand Down

0 comments on commit ecfefd7

Please sign in to comment.