Skip to content

Commit 8286c2b

Browse files
committed
Added safety checks for incorrectly sized buffers being passed
1 parent d89a0c9 commit 8286c2b

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

examples/winit_wrong_sized_buffer.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use winit::event::{Event, WindowEvent};
2+
use winit::event_loop::{ControlFlow, EventLoop};
3+
use winit::window::WindowBuilder;
4+
use softbuffer::GraphicsContext;
5+
6+
const BUFFER_WIDTH: usize = 256;
7+
const BUFFER_HEIGHT: usize = 128;
8+
9+
fn main() {
10+
let event_loop = EventLoop::new();
11+
let window = WindowBuilder::new().build(&event_loop).unwrap();
12+
let mut graphics_context = unsafe { GraphicsContext::new(window) };
13+
14+
event_loop.run(move |event, _, control_flow| {
15+
*control_flow = ControlFlow::Wait;
16+
17+
match event {
18+
Event::RedrawRequested(window_id) if window_id == graphics_context.window().id() => {
19+
let buffer = (0..((BUFFER_WIDTH*BUFFER_HEIGHT) as usize)).map(|index|{
20+
let y = index / (BUFFER_WIDTH as usize);
21+
let x = index % (BUFFER_WIDTH as usize);
22+
let red = x % 255;
23+
let green = y % 255;
24+
let blue = (x*y) % 255;
25+
26+
let color = blue | (green << 8) | (red << 16);
27+
28+
color as u32
29+
}).collect::<Vec<_>>();
30+
31+
graphics_context.set_buffer(&buffer, BUFFER_WIDTH as u16, BUFFER_HEIGHT as u16);
32+
}
33+
Event::WindowEvent {
34+
event: WindowEvent::CloseRequested,
35+
window_id
36+
} if window_id == graphics_context.window().id() => {
37+
*control_flow = ControlFlow::Exit;
38+
},
39+
_ => {}
40+
}
41+
});
42+
}

src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@ impl<W: HasRawWindowHandle> GraphicsContext<W> {
4040

4141
#[inline]
4242
pub fn set_buffer(&mut self, buffer: &[u32], width: u16, height: u16){
43+
if (width as usize)*(height as usize) != buffer.len(){
44+
panic!("The size of the passed buffer is not the correct size. Its length must be exactly width*height.");
45+
}
46+
4347
unsafe {
4448
self.graphics_context_impl.set_buffer(buffer, width, height);
4549
}

0 commit comments

Comments
 (0)