Skip to content

Commit 26dcfa3

Browse files
andresvkorken89
authored andcommitted
histbuf: replace slow modulo operatins
on cortex m0 `%` is extremely costly
1 parent 0ab806d commit 26dcfa3

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

src/histbuf.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,10 @@ where
122122
/// Writes an element to the buffer, overwriting the oldest value.
123123
pub fn write(&mut self, t: T) {
124124
self.data[self.write_at] = t;
125-
self.write_at = (self.write_at + 1) % self.len();
125+
self.write_at = self.write_at + 1;
126+
if self.write_at == self.len() {
127+
self.write_at = 0;
128+
}
126129
}
127130

128131
/// Clones and writes all elements in a slice to the buffer.
@@ -152,7 +155,11 @@ where
152155
/// assert_eq!(x.recent(), &10);
153156
/// ```
154157
pub fn recent(&self) -> &T {
155-
&self.data[(self.write_at + self.len() - 1) % self.len()]
158+
if self.write_at == 0 {
159+
&self.data[(self.len() - 1)]
160+
} else {
161+
&self.data[(self.write_at - 1)]
162+
}
156163
}
157164

158165
/// Returns the array slice backing the buffer, without keeping track

0 commit comments

Comments
 (0)