Skip to content

Commit

Permalink
png: Use transmute instead of align_to
Browse files Browse the repository at this point in the history
  • Loading branch information
not-fl3 committed Sep 7, 2023
1 parent 1abe959 commit 336d36d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 20 deletions.
22 changes: 2 additions & 20 deletions zune-png/src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use crate::filters::de_filter::{
use crate::options::default_chunk_handler;
use crate::utils::{
add_alpha, convert_be_to_target_endian_u16, expand_bits_to_byte, expand_palette, expand_trns,
is_le
is_le, convert_u16_to_u8_slice
};

/// A palette entry.
Expand Down Expand Up @@ -777,26 +777,8 @@ impl<T: ZReaderTrait> PngDecoder<T> {
{
&mut out_u8
} else {
#[inline(always)]
fn align_to_mut(slice: &mut [u16]) -> (&mut [u16], &mut [u8], &mut [u16]) {
// this is safe for two different reasons:
// - the crate compiles with "bytemuck" feature on, proving that we satisfy slice's trait requirements for align_to_mut to be safe
// - align_to_mut from u16 slice to u8 slice is, in fact, safe
#[cfg(not(feature = "bytemuck"))]
{
unsafe { slice.align_to_mut::<u8>() }
}

#[cfg(feature = "bytemuck")]
{
bytemuck::pod_align_to_mut::<u16, u8>(&mut out_u16)
}
}
let (a, b, c) = align_to_mut(&mut out_u16);
let b = convert_u16_to_u8_slice(&mut out_u16);

// a and c should be empty since we do not expect slop bytes on either edge
assert!(a.is_empty());
assert!(c.is_empty());
assert_eq!(b.len(), new_len * 2); // length should be twice that of u8
b
};
Expand Down
11 changes: 11 additions & 0 deletions zune-png/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,3 +350,14 @@ pub(crate) fn add_alpha(input: &[u8], output: &mut [u8], colorspace: PngColor, d
(a, b) => panic!("Unknown combination of depth {a:?} and color type for expand alpha {b:?}")
}
}

pub fn convert_u16_to_u8_slice(slice: &mut [u16]) -> &mut [u8] {
// Converting a u16 slice to a u8 slice is always correct because
// the alignment of the target is smaller.
unsafe {
std::slice::from_raw_parts_mut(
slice.as_ptr() as *mut u8,
slice.len().checked_mul(2).unwrap(),
)
}
}

0 comments on commit 336d36d

Please sign in to comment.