Skip to content

Commit f936714

Browse files
author
Adrià Arrufat
committed
geometry: type ergonomics in rectangle
1 parent 63751bb commit f936714

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/geometry.zig

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ const expectEqualDeep = std.testing.expectEqualDeep;
99

1010
/// A generic rectangle object with some convenience functionality.
1111
pub fn Rectangle(comptime T: type) type {
12+
switch (@typeInfo(T)) {
13+
.Int, .Float => {},
14+
else => @compileError("Unsupported type " ++ @typeName(T) ++ " for Rectangle"),
15+
}
1216
return struct {
1317
const Self = @This();
1418
l: T,
@@ -64,25 +68,25 @@ pub fn Rectangle(comptime T: type) type {
6468
}
6569

6670
/// Returns the width of the rectangle.
67-
pub fn width(self: Self) T {
71+
pub fn width(self: Self) if (@typeInfo(T) == .Int) usize else T {
6872
return if (self.isEmpty()) 0 else switch (@typeInfo(T)) {
69-
.Int => self.r - self.l + 1,
73+
.Int => @intCast(self.r - self.l + 1),
7074
.Float => self.r - self.t,
7175
else => @compileError("Unsupported type " ++ @typeName(T) ++ " for Rectangle"),
7276
};
7377
}
7478

7579
/// Returns the height of the rectangle.
76-
pub fn height(self: Self) T {
80+
pub fn height(self: Self) if (@typeInfo(T) == .Int) usize else T {
7781
return if (self.isEmpty()) 0 else switch (@typeInfo(T)) {
78-
.Int => self.b - self.t + 1,
82+
.Int => @intCast(self.b - self.t + 1),
7983
.Float => self.b - self.t,
8084
else => @compileError("Unsupported type " ++ @typeName(T) ++ " for Rectangle"),
8185
};
8286
}
8387

8488
/// Returns the area of the rectangle
85-
pub fn area(self: Self) T {
89+
pub fn area(self: Self) if (@typeInfo(T) == .Int) usize else T {
8690
return self.height() * self.width();
8791
}
8892

0 commit comments

Comments
 (0)