| 358 | |
| 359 | impl<const N: usize> io::Seek for SegmentedReader<N> { |
| 360 | fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> { |
| 361 | use io::SeekFrom; |
| 362 | |
| 363 | // Get an offset from the start. |
| 364 | let maybe_offset = match pos { |
| 365 | SeekFrom::Start(n) => Some(usize::cast_from(n)), |
| 366 | SeekFrom::End(n) => { |
| 367 | let n = isize::cast_from(n); |
| 368 | self.len().checked_add_signed(n) |
| 369 | } |
| 370 | SeekFrom::Current(n) => { |
| 371 | let n = isize::cast_from(n); |
| 372 | self.overall_ptr.checked_add_signed(n) |
| 373 | } |
| 374 | }; |
| 375 | |
| 376 | // Check for integer overflow, but we don't check our bounds! |
| 377 | // |
| 378 | // The contract for io::Seek denotes that seeking beyond the end |
| 379 | // of the stream is allowed. If we're beyond the end of the stream |
| 380 | // then we won't read back any bytes, but it won't be an error. |
| 381 | let offset = maybe_offset.ok_or_else(|| { |
| 382 | io::Error::new( |
| 383 | io::ErrorKind::InvalidInput, |
| 384 | "Invalid seek to an overflowing position", |
| 385 | ) |
| 386 | })?; |
| 387 | |
| 388 | // Special case we want to be fast, seeking back to the beginning. |
| 389 | if offset == 0 { |
| 390 | self.overall_ptr = 0; |
| 391 | self.segment_ptr = 0; |
| 392 | |
| 393 | return Ok(u64::cast_from(offset)); |
| 394 | } |
| 395 | |
| 396 | // Seek through our segments until we get to the correct offset. |
| 397 | let result = self |
| 398 | .segments |
| 399 | .binary_search_by(|(_s, accum_len)| accum_len.cmp(&offset)); |
| 400 | |
| 401 | self.segment_ptr = match result { |
| 402 | Ok(segment_ptr) => segment_ptr + 1, |
| 403 | Err(segment_ptr) => segment_ptr, |
| 404 | }; |
| 405 | self.overall_ptr = offset; |
| 406 | |
| 407 | Ok(u64::cast_from(offset)) |
| 408 | } |
| 409 | } |
| 410 | } |
| 411 | |