Skip to content

Commit

Permalink
Pre-allocate buffer in remove_extra_data
Browse files Browse the repository at this point in the history
  • Loading branch information
samrat committed Dec 15, 2023
1 parent 765e43c commit 0f88f11
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
1 change: 1 addition & 0 deletions src/darwin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ fn capture(display_info: &DisplayInfo, cg_rect: CGRect) -> Result<RgbaImage> {
let height = cg_image.height();
let clean_buf = remove_extra_data(
width,
height,
cg_image.bytes_per_row(),
Vec::from(cg_image.data().bytes()),
);
Expand Down
18 changes: 14 additions & 4 deletions src/image_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,19 @@ pub fn bgra_to_rgba_image(width: u32, height: u32, buf: Vec<u8>) -> Result<RgbaI
/// https://github.com/nashaofu/screenshots-rs/issues/29
/// https://github.com/nashaofu/screenshots-rs/issues/38
#[cfg(any(target_os = "macos", test))]
pub fn remove_extra_data(width: usize, bytes_per_row: usize, buf: Vec<u8>) -> Vec<u8> {
buf.chunks_exact(bytes_per_row)
.flat_map(|row| row.split_at(width * 4).0.to_owned())
.collect()
pub fn remove_extra_data(
width: usize,
height: usize,
bytes_per_row: usize,
buf: Vec<u8>,
) -> Vec<u8> {
let extra_bytes_per_row = bytes_per_row - width * 4;
let mut result = Vec::with_capacity(buf.len() - extra_bytes_per_row * height);
for row in buf.chunks_exact(bytes_per_row) {
result.extend_from_slice(&row[..width * 4]);
}

result
}

#[cfg(any(target_os = "linux", test))]
Expand Down Expand Up @@ -61,6 +70,7 @@ mod tests {
#[test]
fn extra_data() {
let clean = remove_extra_data(
2,
2,
9,
vec![
Expand Down

0 comments on commit 0f88f11

Please sign in to comment.