pola-rs/polars · error

range start index out of range for slice of length

Error message

range start index {start} out of range for slice of length {len}

What it means

slice_index_fail in polars-utils' range helper replicates stdlib slice-index panics: it aborts when a range's start exceeds the slice length. check_range funnels invalid RangeBounds here, so any API using check_range with start > len triggers this message.

Solutions

  1. Clamp start to the collection length before slicing: start.min(len)
  2. Check len == 0 or start >= len and return an empty result instead of slicing
  3. Validate user-supplied start indices against the actual size first
  4. Trace the caller of check_range to fix the length computation upstream

Example fix

// before
let out = check_range(start..end, ..len);
// after
let start = start.min(len);
let out = check_range(start..end, ..len);
Defensive patterns

Strategy: validation

Validate before calling

def safe_slice(start, end, len_):
    start = max(0, min(start, len_))
    end = max(start, min(end, len_))
    return start, end

Prevention

When it happens

Trigger: Calling an API that indexes/slices via check_range with a RangeFrom or Range whose start exceeds the collection length (e.g. slicing a row/column collection at an offset past the end).

Common situations: Computing offsets from mismatched lengths (empty input data); off-by-one when slicing after a filter; passing user-supplied offsets without clamping.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/f9861893f2afc742. Report an issue: GitHub.

Appendix: source

Thrown at crates/polars-utils/src/range.rs:6

use std::ops;

// Copied from the stdlib.
fn slice_index_fail(start: usize, end: usize, len: usize) -> ! {
    if start > len {
        panic!("range start index {start} out of range for slice of length {len}",)
    }

    if end > len {
        panic!("range end index {end} out of range for slice of length {len}",)
    }

    if start > end {
        panic!("slice index starts at {start} but ends at {end}",)
    }

    // Only reachable if the range was a `RangeInclusive` or a
    // `RangeToInclusive`, with `end == len`.
    panic!("range end index {end} out of range for slice of length {len}",)
}

#[must_use]
pub fn check_range<R>(range: R, bounds: ops::RangeTo<usize>) -> ops::Range<usize>
where

View on GitHub (pinned to fe841f959e)