wayland: Avoid allocating more than 2 buffers

This commit is contained in:
Ian Douglas Scott 2022-12-20 15:05:20 -08:00 committed by Jeremy Soller
parent cdfae58510
commit dbd4e796f1

View file

@ -1,5 +1,6 @@
use crate::{error::unwrap, GraphicsContextImpl, SwBufError}; use crate::{error::unwrap, GraphicsContextImpl, SwBufError};
use raw_window_handle::{WaylandDisplayHandle, WaylandWindowHandle}; use raw_window_handle::{WaylandDisplayHandle, WaylandWindowHandle};
use std::collections::VecDeque;
use wayland_client::{ use wayland_client::{
backend::{Backend, ObjectId}, backend::{Backend, ObjectId},
globals::{registry_queue_init, GlobalListContents}, globals::{registry_queue_init, GlobalListContents},
@ -17,7 +18,8 @@ pub struct WaylandImpl {
qh: QueueHandle<State>, qh: QueueHandle<State>,
surface: wl_surface::WlSurface, surface: wl_surface::WlSurface,
shm: wl_shm::WlShm, shm: wl_shm::WlShm,
buffers: Vec<WaylandBuffer>, // 0-2 buffers
buffers: VecDeque<WaylandBuffer>,
} }
impl WaylandImpl { impl WaylandImpl {
@ -53,20 +55,28 @@ impl WaylandImpl {
qh, qh,
surface, surface,
shm, shm,
buffers: Vec::new(), buffers: Default::default(),
}) })
} }
// Allocate or reuse a buffer of the given size // Allocate or reuse a buffer of the given size
fn buffer(&mut self, width: i32, height: i32) -> &WaylandBuffer { fn buffer(&mut self, width: i32, height: i32) -> &WaylandBuffer {
if let Some(idx) = self.buffers.iter().position(|i| i.released()) { let buffer = if let Some(mut buffer) = self.buffers.pop_front() {
self.buffers[idx].resize(width, height); if buffer.released() {
&mut self.buffers[idx] buffer.resize(width, height);
buffer
} else {
// If we have more than 1 unreleased buffer, destroy it
if self.buffers.len() == 0 {
self.buffers.push_back(buffer);
}
WaylandBuffer::new(&self.shm, width, height, &self.qh)
}
} else { } else {
self.buffers WaylandBuffer::new(&self.shm, width, height, &self.qh)
.push(WaylandBuffer::new(&self.shm, width, height, &self.qh)); };
self.buffers.last().unwrap() self.buffers.push_back(buffer);
} self.buffers.back().unwrap()
} }
} }