subtensor icon indicating copy to clipboard operation
subtensor copied to clipboard

Ban direct indexing in `Math.rs`

Open JohnReedV opened this issue 8 months ago • 1 comments

Ban direct indexing in subtensor/src/math.rs

Problem:
The remaining #[allow(clippy::indexing_slicing)] live in math.rs, allowing potential panics in vec[idx] and slice[...].

Proposal:

  1. Remove #[allow(clippy::indexing_slicing)] from pallets/subtensor/src/math.rs.
  2. Replace every vec[idx] or slice[a..b] with a safe alternative, for example:
    // Before — can panic if `i >= vector.len()`
    idxs.sort_by_key(|&i| &vector[i]);
    
    // After — returns zero on OOB
    idxs.sort_by_key(|&i| {
        vector
            .get(i)
            .copied()
            .unwrap_or(I32F32::saturating_from_num(0))
    });```
    

JohnReedV avatar May 07 '25 17:05 JohnReedV

get() is basically fallible index slicing but without the panic if it's out of bounds, and sometimes it really isn't very clear what should be done when you have an index that's out of bounds. It could be the case that you need to return an Option or Result, which means you'd need to refactor every function call to handle the null case.

keithtensor avatar May 14 '25 15:05 keithtensor