Skip to content

Commit

Permalink
Merge pull request #461 from dhardy/fill-zero-len
Browse files Browse the repository at this point in the history
Fix #460: fill shouldn't panic on zero-length slices
  • Loading branch information
dhardy authored May 16, 2018
2 parents 89b268e + 1509f9d commit 5953334
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -702,12 +702,19 @@ macro_rules! impl_as_byte_slice {
($t:ty) => {
impl AsByteSliceMut for [$t] {
fn as_byte_slice_mut(&mut self) -> &mut [u8] {
unsafe {
slice::from_raw_parts_mut(&mut self[0]
as *mut $t
as *mut u8,
self.len() * mem::size_of::<$t>()
)
if self.len() == 0 {
unsafe {
// must not use null pointer
slice::from_raw_parts_mut(0x1 as *mut u8, 0)
}
} else {
unsafe {
slice::from_raw_parts_mut(&mut self[0]
as *mut $t
as *mut u8,
self.len() * mem::size_of::<$t>()
)
}
}
}

Expand Down Expand Up @@ -762,7 +769,7 @@ macro_rules! impl_as_byte_slice_arrays {
}
};
}
impl_as_byte_slice_arrays!(32, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,);
impl_as_byte_slice_arrays!(32, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,);
impl_as_byte_slice_arrays!(!div 4096, N,N,N,N,N,N,N,);

/// Iterator which will generate a stream of random items.
Expand Down Expand Up @@ -1061,6 +1068,14 @@ mod test {
assert_eq!(array, [x as u32, (x >> 32) as u32]);
assert_eq!(rng.next_u32(), x as u32);
}

#[test]
fn test_fill_empty() {
let mut array = [0u32; 0];
let mut rng = StepRng::new(0, 1);
rng.fill(&mut array);
rng.fill(&mut array[..]);
}

#[test]
fn test_gen_range() {
Expand Down

0 comments on commit 5953334

Please sign in to comment.