Utilize bytes::Bytes for images

This commit is contained in:
Bajix 2024-03-27 12:54:01 -07:00 committed by Héctor Ramón Jiménez
parent 89892f1760
commit 8d27af24a7
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
3 changed files with 8 additions and 56 deletions

View file

@ -136,6 +136,7 @@ iced_winit = { version = "0.13.0-dev", path = "winit" }
async-std = "1.0"
bitflags = "2.0"
bytes = "1.6"
bytemuck = { version = "1.0", features = ["derive"] }
cosmic-text = "0.10"
dark-light = "1.0"

View file

@ -19,6 +19,7 @@ advanced = []
[dependencies]
bitflags.workspace = true
bytes.workspace = true
glam.workspace = true
log.workspace = true
num-traits.workspace = true

View file

@ -1,10 +1,11 @@
//! Load and draw raster graphics.
pub use bytes::Bytes;
use crate::{Rectangle, Size};
use rustc_hash::FxHasher;
use std::hash::{Hash, Hasher as _};
use std::path::PathBuf;
use std::sync::Arc;
/// A handle of some image data.
#[derive(Debug, Clone, PartialEq, Eq)]
@ -29,12 +30,12 @@ impl Handle {
pub fn from_pixels(
width: u32,
height: u32,
pixels: impl AsRef<[u8]> + Send + Sync + 'static,
pixels: impl Into<Bytes>,
) -> Handle {
Self::from_data(Data::Rgba {
width,
height,
pixels: Bytes::new(pixels),
pixels: pixels.into(),
})
}
@ -44,10 +45,8 @@ impl Handle {
///
/// This is useful if you already have your image loaded in-memory, maybe
/// because you downloaded or generated it procedurally.
pub fn from_memory(
bytes: impl AsRef<[u8]> + Send + Sync + 'static,
) -> Handle {
Self::from_data(Data::Bytes(Bytes::new(bytes)))
pub fn from_memory(bytes: impl Into<Bytes>) -> Handle {
Self::from_data(Data::Bytes(bytes.into()))
}
fn from_data(data: Data) -> Handle {
@ -86,55 +85,6 @@ impl Hash for Handle {
}
}
/// A wrapper around raw image data.
///
/// It behaves like a `&[u8]`.
#[derive(Clone)]
pub struct Bytes(Arc<dyn AsRef<[u8]> + Send + Sync + 'static>);
impl Bytes {
/// Creates new [`Bytes`] around `data`.
pub fn new(data: impl AsRef<[u8]> + Send + Sync + 'static) -> Self {
Self(Arc::new(data))
}
}
impl std::fmt::Debug for Bytes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.as_ref().as_ref().fmt(f)
}
}
impl std::hash::Hash for Bytes {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.as_ref().as_ref().hash(state);
}
}
impl PartialEq for Bytes {
fn eq(&self, other: &Self) -> bool {
let a = self.as_ref();
let b = other.as_ref();
core::ptr::eq(a, b) || a == b
}
}
impl Eq for Bytes {}
impl AsRef<[u8]> for Bytes {
fn as_ref(&self) -> &[u8] {
self.0.as_ref().as_ref()
}
}
impl std::ops::Deref for Bytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
self.0.as_ref().as_ref()
}
}
/// The data of a raster image.
#[derive(Clone, PartialEq, Eq, Hash)]
pub enum Data {