From a8fc644d6c8ed6809c20a92e1fa5960cee46cbfd Mon Sep 17 00:00:00 2001 From: Simon Gardling Date: Thu, 27 Mar 2025 14:37:36 -0400 Subject: [PATCH] replace common index code --- src/buffer.rs | 5 +---- src/grid.rs | 7 ++----- src/util.rs | 9 +++++++++ 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/buffer.rs b/src/buffer.rs index 09308e0..63eef0a 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -16,10 +16,7 @@ impl Buf { // Truncate x and y and return a corresponding index into the data slice. const fn index(&self, x: f32, y: f32) -> usize { - // x/y can come in negative, hence we shift them by width/height. - let i = (x + self.width as f32) as usize & (self.width - 1); - let j = (y + self.height as f32) as usize & (self.height - 1); - j * self.width + i + crate::util::index(self.width, self.height, x, y) } // Get the buffer value at a given position. The implementation effectively treats data as periodic, hence any finite position will produce a value. diff --git a/src/grid.rs b/src/grid.rs index 3ac5443..848e721 100644 --- a/src/grid.rs +++ b/src/grid.rs @@ -78,11 +78,8 @@ impl Grid { } // Truncate x and y and return a corresponding index into the data slice. - fn index(&self, x: f32, y: f32) -> usize { - // x/y can come in negative, hence we shift them by width/height. - let i = (x + self.width as f32) as usize & (self.width - 1); - let j = (y + self.height as f32) as usize & (self.height - 1); - j * self.width + i + const fn index(&self, x: f32, y: f32) -> usize { + crate::util::index(self.width, self.height, x, y) } // Add a value to the grid data at a given position. diff --git a/src/util.rs b/src/util.rs index cc43420..542bf9f 100644 --- a/src/util.rs +++ b/src/util.rs @@ -2,3 +2,12 @@ pub fn wrap(x: f32, max: f32) -> f32 { x - max * ((x > max) as i32 as f32 - (x < 0.0_f32) as i32 as f32) } + +// Truncate x and y and return a corresponding index into the data slice. +#[inline] +pub const fn index(width: usize, height: usize, x: f32, y: f32) -> usize { + // x/y can come in negative, hence we shift them by width/height. + let i = (x + width as f32) as usize & (width - 1); + let j = (y + height as f32) as usize & (height - 1); + j * width + i +}