Use u32::{from_be_bytes,to_be_bytes} builtins

This commit is contained in:
Ivan Smirnov 2022-01-02 23:30:28 +03:00
parent d763e1d62c
commit 0b76352b22
2 changed files with 10 additions and 24 deletions

View file

@ -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;

View file

@ -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) {