Skip to content

Commit c1d0ca3

Browse files
Fix unsoundness in insert_score_depth, insert_score, and Stack::offset
- Replace unsafe get_unchecked_mut with safe indexing in insert_score_depth and insert_score, which provides automatic bounds checking via the existing IndexMut trait implementation - Add debug_assert bounds check and safety documentation to Stack::offset - Add tests verifying out-of-bounds panics for insert_score_depth and insert_score Co-authored-by: chase-manning <53957795+chase-manning@users.noreply.github.com>
1 parent fa21da4 commit c1d0ca3

File tree

2 files changed

+30
-9
lines changed

2 files changed

+30
-9
lines changed

pleco_engine/src/root_moves/root_moves_list.rs

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -93,19 +93,15 @@ impl RootMoveList {
9393

9494
#[inline]
9595
pub fn insert_score_depth(&mut self, index: usize, score: i32, depth: i16) {
96-
unsafe {
97-
let rm: &mut RootMove = self.get_unchecked_mut(index);
98-
rm.score = score;
99-
rm.depth_reached = depth;
100-
}
96+
let rm: &mut RootMove = &mut self[index];
97+
rm.score = score;
98+
rm.depth_reached = depth;
10199
}
102100

103101
#[inline]
104102
pub fn insert_score(&mut self, index: usize, score: i32) {
105-
unsafe {
106-
let rm: &mut RootMove = self.get_unchecked_mut(index);
107-
rm.score = score;
108-
}
103+
let rm: &mut RootMove = &mut self[index];
104+
rm.score = score;
109105
}
110106

111107
pub fn find(&mut self, mov: BitMove) -> Option<&mut RootMove> {
@@ -196,3 +192,22 @@ impl<'a> IntoIterator for &'a RootMoveList {
196192
impl<'a> ExactSizeIterator for MoveIter<'a> {}
197193

198194
impl<'a> FusedIterator for MoveIter<'a> {}
195+
196+
#[cfg(test)]
197+
mod tests {
198+
use super::*;
199+
200+
#[test]
201+
#[should_panic]
202+
fn insert_score_depth_out_of_bounds() {
203+
let mut list = RootMoveList::new();
204+
list.insert_score_depth(1000, 100, 10);
205+
}
206+
207+
#[test]
208+
#[should_panic]
209+
fn insert_score_out_of_bounds() {
210+
let mut list = RootMoveList::new();
211+
list.insert_score(1000, 100);
212+
}
213+
}

pleco_engine/src/search/mod.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,9 +97,15 @@ pub struct Stack {
9797

9898
impl Stack {
9999
/// Get the next ply at an offset.
100+
///
101+
/// # Safety
102+
///
103+
/// The caller must ensure that the resulting pointer after applying `count`
104+
/// remains within the bounds of the containing `ThreadStack` array.
100105
pub fn offset(&mut self, count: isize) -> &mut Stack {
101106
unsafe {
102107
let ptr: *mut Stack = self as *mut Stack;
108+
debug_assert!((count.unsigned_abs()) < THREAD_STACK_SIZE);
103109
&mut *ptr.offset(count)
104110
}
105111
}

0 commit comments

Comments
 (0)