Skip to content

Commit 5953334

Browse files
authored
Merge pull request #461 from dhardy/fill-zero-len
Fix #460: fill shouldn't panic on zero-length slices
2 parents 89b268e + 1509f9d commit 5953334

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

src/lib.rs

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -702,12 +702,19 @@ macro_rules! impl_as_byte_slice {
702702
($t:ty) => {
703703
impl AsByteSliceMut for [$t] {
704704
fn as_byte_slice_mut(&mut self) -> &mut [u8] {
705-
unsafe {
706-
slice::from_raw_parts_mut(&mut self[0]
707-
as *mut $t
708-
as *mut u8,
709-
self.len() * mem::size_of::<$t>()
710-
)
705+
if self.len() == 0 {
706+
unsafe {
707+
// must not use null pointer
708+
slice::from_raw_parts_mut(0x1 as *mut u8, 0)
709+
}
710+
} else {
711+
unsafe {
712+
slice::from_raw_parts_mut(&mut self[0]
713+
as *mut $t
714+
as *mut u8,
715+
self.len() * mem::size_of::<$t>()
716+
)
717+
}
711718
}
712719
}
713720

@@ -762,7 +769,7 @@ macro_rules! impl_as_byte_slice_arrays {
762769
}
763770
};
764771
}
765-
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,);
772+
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,);
766773
impl_as_byte_slice_arrays!(!div 4096, N,N,N,N,N,N,N,);
767774

768775
/// Iterator which will generate a stream of random items.
@@ -1061,6 +1068,14 @@ mod test {
10611068
assert_eq!(array, [x as u32, (x >> 32) as u32]);
10621069
assert_eq!(rng.next_u32(), x as u32);
10631070
}
1071+
1072+
#[test]
1073+
fn test_fill_empty() {
1074+
let mut array = [0u32; 0];
1075+
let mut rng = StepRng::new(0, 1);
1076+
rng.fill(&mut array);
1077+
rng.fill(&mut array[..]);
1078+
}
10641079

10651080
#[test]
10661081
fn test_gen_range() {

0 commit comments

Comments
 (0)