Skip to content

Commit 6e44260

Browse files
authored
Mark write_to_spare_capacity_of_vec as unsafe
And add safety comment
1 parent 11eeb01 commit 6e44260

File tree

1 file changed

+27
-18
lines changed

1 file changed

+27
-18
lines changed

src/mem.rs

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -362,12 +362,15 @@ impl Compress {
362362
output: &mut Vec<u8>,
363363
flush: FlushCompress,
364364
) -> Result<Status, CompressError> {
365-
write_to_spare_capacity_of_vec(output, |out| {
366-
let before = self.total_out();
367-
let ret = self.compress_uninit(input, out, flush);
368-
let bytes_written = self.total_out() - before;
369-
(bytes_written as usize, ret)
370-
})
365+
// SAFETY: bytes_written is the number of bytes writte into `out`
366+
unsafe {
367+
write_to_spare_capacity_of_vec(output, |out| {
368+
let before = self.total_out();
369+
let ret = self.compress_uninit(input, out, flush);
370+
let bytes_written = self.total_out() - before;
371+
(bytes_written as usize, ret)
372+
})
373+
}
371374
}
372375
}
373376

@@ -496,12 +499,15 @@ impl Decompress {
496499
output: &mut Vec<u8>,
497500
flush: FlushDecompress,
498501
) -> Result<Status, DecompressError> {
499-
write_to_spare_capacity_of_vec(output, |out| {
500-
let before = self.total_out();
501-
let ret = self.decompress_uninit(input, out, flush);
502-
let bytes_written = self.total_out() - before;
503-
(bytes_written as usize, ret)
504-
})
502+
// SAFETY: bytes_written is the number of bytes writte into `out`
503+
unsafe {
504+
write_to_spare_capacity_of_vec(output, |out| {
505+
let before = self.total_out();
506+
let ret = self.decompress_uninit(input, out, flush);
507+
let bytes_written = self.total_out() - before;
508+
(bytes_written as usize, ret)
509+
})
510+
}
505511
}
506512

507513
/// Specifies the decompression dictionary to use.
@@ -601,19 +607,22 @@ impl fmt::Display for CompressError {
601607
///
602608
/// `writer` needs to return the number of bytes written (and can also return
603609
/// another arbitrary return value).
604-
fn write_to_spare_capacity_of_vec<T>(
610+
///
611+
/// # Safety:
612+
///
613+
/// The length returned by the `writer` must be equal to actual number of bytes written
614+
/// to the uninitialized slice passed in and initialized.
615+
unsafe fn write_to_spare_capacity_of_vec<T>(
605616
output: &mut Vec<u8>,
606617
writer: impl FnOnce(&mut [MaybeUninit<u8>]) -> (usize, T),
607618
) -> T {
608619
let cap = output.capacity();
609620
let len = output.len();
610621

611-
unsafe {
612-
let (bytes_written, ret) = writer(output.spare_capacity_mut());
613-
output.set_len(cap.min(len + bytes_written)); // Sanitizes `bytes_written`.
622+
let (bytes_written, ret) = writer(output.spare_capacity_mut());
623+
output.set_len(cap.min(len + bytes_written)); // Sanitizes `bytes_written`.
614624

615-
ret
616-
}
625+
ret
617626
}
618627

619628
#[cfg(test)]

0 commit comments

Comments
 (0)