fast image operations
add uninit and alloc
bendn 2025-01-31
parent a994559 · commit b23372e
-rw-r--r--src/indexed.rs4
-rw-r--r--src/indexed/builder.rs31
-rw-r--r--src/lib.rs1
3 files changed, 33 insertions, 3 deletions
diff --git a/src/indexed.rs b/src/indexed.rs
index f2fc00e..dfa00ac 100644
--- a/src/indexed.rs
+++ b/src/indexed.rs
@@ -5,7 +5,7 @@ mod builder;
use crate::Image;
#[allow(non_camel_case_types)]
-trait uint: Copy + TryInto<usize> {
+trait uint: Default + Copy + TryInto<usize> {
fn nat(self) -> usize {
self.try_into().ok().unwrap()
}
@@ -16,7 +16,7 @@ macro_rules! int {
$(impl uint for $t {})+
};
}
-int!(u8 u16 u32 u64 u128);
+int!(u8 u16 u32 u64 usize u128);
/// An image with a palette.
#[derive(Clone)]
diff --git a/src/indexed/builder.rs b/src/indexed/builder.rs
index 90bf3c5..c774712 100644
--- a/src/indexed/builder.rs
+++ b/src/indexed/builder.rs
@@ -1,5 +1,5 @@
use super::{uint, IndexedImage as Image};
-use std::marker::PhantomData;
+use std::{marker::PhantomData, mem::MaybeUninit};
impl<B, P> Image<B, P> {
/// creates a builder
pub const fn build<I, J>(w: u32, h: u32) -> Builder<B, P>
@@ -56,4 +56,33 @@ impl<B, P> Builder<B, P> {
)
.unwrap()
}
+
+ /// Allocates a zeroed buffer.
+ #[track_caller]
+ #[must_use]
+ pub fn alloc<I: uint, J>(self) -> Image<Box<[I]>, P>
+ where
+ P: AsRef<[J]>,
+ {
+ let palette = self.palette.expect("require palette");
+ assert!(palette.as_ref().len() != 0, "need some palette");
+ Image {
+ buffer: crate::Image::build(self.width, self.height).buf(
+ vec![I::default(); self.width as usize * self.height as usize].into_boxed_slice(),
+ ),
+ palette,
+ }
+ }
+
+ pub fn uninit<I: uint, J>(self) -> Image<Box<[MaybeUninit<I>]>, P>
+ where
+ P: AsRef<[J]>,
+ {
+ Image {
+ buffer: crate::Image::build(self.width, self.height).buf(Box::new_uninit_slice(
+ self.width as usize * self.height as usize,
+ )),
+ palette: self.palette.expect("require palette"),
+ }
+ }
}
diff --git a/src/lib.rs b/src/lib.rs
index 2c3ea14..14ae1e5 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -64,6 +64,7 @@
doc_auto_cfg,
const_option,
array_chunks,
+ new_uninit,
iter_chain,
let_chains,
try_blocks,