From 0b76352b22f4dcb112e06cd3b3cc3969407b92e2 Mon Sep 17 00:00:00 2001 From: Ivan Smirnov Date: Sun, 2 Jan 2022 23:30:28 +0300 Subject: [PATCH] Use u32::{from_be_bytes,to_be_bytes} builtins --- src/consts.rs | 3 +-- src/header.rs | 31 +++++++++---------------------- 2 files changed, 10 insertions(+), 24 deletions(-) diff --git a/src/consts.rs b/src/consts.rs index b143f90..2281c24 100644 --- a/src/consts.rs +++ b/src/consts.rs @@ -12,7 +12,6 @@ pub const QOI_HEADER_SIZE: usize = 14; pub const QOI_PADDING: [u8; 8] = [0, 0, 0, 0, 0, 0, 0, 0x01]; // 7 zeros and one 0x01 marker pub const QOI_PADDING_SIZE: usize = 8; -pub const QOI_MAGIC: u32 = - (b'q' as u32) << 24 | (b'o' as u32) << 16 | (b'i' as u32) << 8 | (b'f' as u32); +pub const QOI_MAGIC: u32 = u32::from_be_bytes(*b"qoif"); pub const QOI_PIXELS_MAX: usize = 400_000_000; diff --git a/src/header.rs b/src/header.rs index a9cfc0d..e59e658 100644 --- a/src/header.rs +++ b/src/header.rs @@ -1,3 +1,5 @@ +use bytemuck::cast_slice; + use crate::colorspace::ColorSpace; use crate::consts::{QOI_HEADER_SIZE, QOI_MAGIC, QOI_PIXELS_MAX}; use crate::error::{Error, Result}; @@ -18,22 +20,6 @@ impl Default for Header { } } -#[inline(always)] -#[allow(clippy::cast_possible_truncation)] -const fn u32_to_be(v: u32) -> [u8; 4] { - [ - ((0xff00_0000 & v) >> 24) as u8, - ((0x00ff_0000 & v) >> 16) as u8, - ((0xff00 & v) >> 8) as u8, - (0x00ff & v) as u8, - ] -} - -#[inline(always)] -const fn u32_from_be(v: &[u8]) -> u32 { - ((v[0] as u32) << 24) | ((v[1] as u32) << 16) | ((v[2] as u32) << 8) | (v[3] as u32) -} - impl Header { #[inline] pub const fn new(width: u32, height: u32, channels: u8) -> Self { @@ -54,9 +40,9 @@ impl Header { #[inline] pub(crate) fn encode(&self) -> [u8; QOI_HEADER_SIZE] { let mut out = [0; QOI_HEADER_SIZE]; - out[..4].copy_from_slice(&u32_to_be(QOI_MAGIC)); - out[4..8].copy_from_slice(&u32_to_be(self.width)); - out[8..12].copy_from_slice(&u32_to_be(self.height)); + out[..4].copy_from_slice(&QOI_MAGIC.to_be_bytes()); + out[4..8].copy_from_slice(&self.width.to_be_bytes()); + out[8..12].copy_from_slice(&self.height.to_be_bytes()); out[12] = self.channels; out[13] = self.colorspace.into(); out @@ -68,9 +54,10 @@ impl Header { if unlikely(data.len() < QOI_HEADER_SIZE) { return Err(Error::InputBufferTooSmall { size: data.len(), required: QOI_HEADER_SIZE }); } - let magic = u32_from_be(&data[..4]); - let width = u32_from_be(&data[4..8]); - let height = u32_from_be(&data[8..12]); + let v = cast_slice::<_, [u8; 4]>(&data[..12]); + let magic = u32::from_be_bytes(v[0]); + let width = u32::from_be_bytes(v[1]); + let height = u32::from_be_bytes(v[2]); let channels = data[12]; let colorspace = ColorSpace::try_from(data[13])?; if unlikely(magic != QOI_MAGIC) {