Skip to content

Commit

Permalink
perf: faster saturating add for RoomCoordinate
Browse files Browse the repository at this point in the history
  • Loading branch information
khoover committed Oct 14, 2024
1 parent ada73d8 commit b27b803
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/local/room_coordinate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ impl Error for OutOfBoundsError {}
pub struct RoomCoordinate(u8);

impl RoomCoordinate {
pub const MAX: Self = Self(ROOM_SIZE - 1);
pub const MIN: Self = Self(0);

/// Create a `RoomCoordinate` from a `u8`, returning an error if the
/// coordinate is not in the valid room size range
#[inline]
Expand Down Expand Up @@ -126,9 +129,13 @@ impl RoomCoordinate {
/// ```
pub fn saturating_add(self, rhs: i8) -> RoomCoordinate {
self.assume_size_constraint();
let result = self.0.saturating_add_signed(rhs).min(ROOM_SIZE - 1);
// Optimizer will see the return is always Ok
RoomCoordinate::new(result).unwrap_throw()
let (res, overflow) = self.0.overflowing_add_signed(rhs);
if overflow {
RoomCoordinate::MIN
} else {
// Optimizer will see the return is always Ok
RoomCoordinate::new(res.min(ROOM_SIZE - 1)).unwrap_throw()
}
}
}

Expand Down

0 comments on commit b27b803

Please sign in to comment.