Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Handle overflow properly in core::slice
core::slice was originally written to tolerate overflow (notably, with slices of zero-sized elements), but it was never updated to use wrapping arithmetic when overflow traps were added. Also correctly handle the case of calling .nth() on an Iter with a zero-sized element type. The iterator was assuming that the pointer value of the returned reference was meaningful, but that's not true for zero-sized elements. Fixes #25016.
- Loading branch information
Showing
2 changed files
with
46 additions
and
39 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT | ||
// file at the top-level directory of this distribution and at | ||
// http://rust-lang.org/COPYRIGHT. | ||
// | ||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | ||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | ||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | ||
// option. This file may not be copied, modified, or distributed | ||
// except according to those terms. | ||
|
||
// compile-flags: -C debug-assertions | ||
|
||
use std::slice; | ||
|
||
pub fn main() { | ||
// In a slice of zero-size elements the pointer is meaningless. | ||
// Ensure iteration still works even if the pointer is at the end of the address space. | ||
let slice: &[()] = unsafe { slice::from_raw_parts(-5isize as *const (), 10) }; | ||
assert_eq!(slice.len(), 10); | ||
assert_eq!(slice.iter().count(), 10); | ||
|
||
// .nth() on the iterator should also behave correctly | ||
let mut it = slice.iter(); | ||
assert!(it.nth(5).is_some()); | ||
assert_eq!(it.count(), 4); | ||
|
||
let slice: &mut [()] = unsafe { slice::from_raw_parts_mut(-5isize as *mut (), 10) }; | ||
assert_eq!(slice.len(), 10); | ||
assert_eq!(slice.iter_mut().count(), 10); | ||
|
||
let mut it = slice.iter_mut(); | ||
assert!(it.nth(5).is_some()); | ||
assert_eq!(it.count(), 4); | ||
} |