{"record":{"id":"552ede30136e00a7","repo":"tracel-ai/burn","slug":"index-out-of-bounds-for-inmemdataset-index","errorCode":null,"errorMessage":"Index out of bounds for InMemDataset: {index} >= {}","messagePattern":"Index out of bounds for InMemDataset: (.+?) >= (.+?)","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/burn-dataset/src/dataset/in_memory.rs","lineNumber":30,"sourceCode":"pub struct InMemDataset<I> {\n    items: Vec<I>,\n}\n\nimpl<I> InMemDataset<I> {\n    /// Creates a new in memory dataset from the given items.\n    pub fn new(items: Vec<I>) -> Self {\n        InMemDataset { items }\n    }\n}\n\nimpl<I> Dataset<I> for InMemDataset<I>\nwhere\n    I: Clone + Send + Sync,\n{\n    fn get(&self, index: usize) -> Result<I, DatasetError> {\n        match self.items.get(index) {\n            Some(item) => Ok(item.clone()),\n            None => panic!(\n                \"Index out of bounds for InMemDataset: {index} >= {}\",\n                self.items.len()\n            ),\n        }\n    }\n    fn len(&self) -> usize {\n        self.items.len()\n    }\n}\n\nimpl<I> InMemDataset<I>\nwhere\n    I: Clone + DeserializeOwned,\n{\n    /// Create from a dataset. All items are loaded in memory.\n    pub fn from_dataset<E>(dataset: &impl Dataset<I, E>) -> Self\n    where\n        E: std::error::Error + Send + Sync + 'static,","sourceCodeStart":12,"sourceCodeEnd":48,"githubUrl":"https://github.com/tracel-ai/burn/blob/d16f7ba2ed0d41408189384044cc886fb4c8f957/crates/burn-dataset/src/dataset/in_memory.rs#L12-L48","documentation":"`InMemDataset::get` indexes into an in-memory `Vec` of items and panics when `index` is beyond the dataset length instead of returning a `DatasetError`. It is thrown from the `Dataset` trait's `get` implementation, so any code doing `dataset.get(i)` with `i >= dataset.len()` aborts.","triggerScenarios":"Calling `dataset.get(index)` (directly or via iterators/batching/transforms) where `index >= InMemDataset::len()`; empty dataset accessed with index 0; off-by-one loops like `for i in 0..=dataset.len()`.","commonSituations":"Splitting data manually with wrong bounds; loading an empty file/record source producing a zero-length dataset; batch-size loops that compute `len/ batch_size` and then index the remainder without a guard; changed dataset size after data updates.","solutions":["Check `index < dataset.len()` before calling `get`, or iterate with a bounded range `0..dataset.len()`.","Verify the dataset loaded as expected (log `dataset.len()`; an unexpected 0 means the source file/path/records are wrong).","Use `dataset.get(...)` only through APIs that respect bounds (e.g. iterators, sampler with replacement=... sized correctly).","Catch/avoid upstream: prefer `Dataset::iter()` or window/sampler transforms that compute valid indices."],"exampleFix":"// before\nfor i in 0..num_samples {\n    let item = dataset.get(i).unwrap(); // panics when i >= dataset.len()\n}\n\n// after\nlet num_samples = dataset.len().min(num_samples);\nfor i in 0..num_samples {\n    let item = dataset.get(i)?;\n}","handlingStrategy":"validation","validationCode":"if index >= dataset.len() {\n    return Err(DatasetError::InvalidArgument(format!(\"index {index} out of bounds (len={})\", dataset.len())));\n}\nlet item = dataset.get(index)?;","typeGuard":null,"tryCatchPattern":"// panics, not Result; pre-check instead\nlet item = if index < dataset.len() { Some(dataset.get(index).ok()) } else { None };","preventionTips":["Always derive loop bounds from `dataset.len()` at the call site","Beware `0..=len` off-by-one loops; use half-open ranges","Log dataset length after loading to catch empty/partially loaded datasets","Prefer `dataset.iter()` over manual indexing where possible"],"tags":["dataset","index-out-of-bounds","burn","rust"],"backgroundTag":"dataset-index-out-of-bounds","analyzedSha":"d16f7ba2ed0d41408189384044cc886fb4c8f957","analyzedAt":"2026-09-05T13:19:14.260Z","contentChangedAt":"2026-09-05T13:19:14.260Z","schemaVersion":2},"datasetVersion":"2026-09-12T17:17:11.597Z"}