cg: Require non-zero width/height; panic instead of segfault

Fixes https://github.com/rust-windowing/softbuffer/issues/124.
This commit is contained in:
Ian Douglas Scott 2023-07-24 18:24:23 -07:00
parent 1f326b2199
commit e10c360929

View file

@ -27,8 +27,7 @@ pub struct CGImpl {
layer: CALayer, layer: CALayer,
window: id, window: id,
color_space: CGColorSpace, color_space: CGColorSpace,
width: u32, size: Option<(NonZeroU32, NonZeroU32)>,
height: u32,
} }
impl CGImpl { impl CGImpl {
@ -52,20 +51,21 @@ impl CGImpl {
layer, layer,
window, window,
color_space, color_space,
width: 0, size: None,
height: 0,
}) })
} }
pub fn resize(&mut self, width: NonZeroU32, height: NonZeroU32) -> Result<(), SoftBufferError> { pub fn resize(&mut self, width: NonZeroU32, height: NonZeroU32) -> Result<(), SoftBufferError> {
self.width = width.get(); self.size = Some((width, height));
self.height = height.get();
Ok(()) Ok(())
} }
pub fn buffer_mut(&mut self) -> Result<BufferImpl, SoftBufferError> { pub fn buffer_mut(&mut self) -> Result<BufferImpl, SoftBufferError> {
let (width, height) = self
.size
.expect("Must set size of surface before calling `buffer_mut()`");
Ok(BufferImpl { Ok(BufferImpl {
buffer: vec![0; self.width as usize * self.height as usize], buffer: vec![0; width.get() as usize * height.get() as usize],
imp: self, imp: self,
}) })
} }
@ -98,12 +98,13 @@ impl<'a> BufferImpl<'a> {
pub fn present(self) -> Result<(), SoftBufferError> { pub fn present(self) -> Result<(), SoftBufferError> {
let data_provider = CGDataProvider::from_buffer(Arc::new(Buffer(self.buffer))); let data_provider = CGDataProvider::from_buffer(Arc::new(Buffer(self.buffer)));
let (width, height) = self.imp.size.unwrap();
let image = CGImage::new( let image = CGImage::new(
self.imp.width as usize, width.get() as usize,
self.imp.height as usize, height.get() as usize,
8, 8,
32, 32,
(self.imp.width * 4) as usize, (width.get() * 4) as usize,
&self.imp.color_space, &self.imp.color_space,
kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
&data_provider, &data_provider,