Simplify refcell usage

This commit is contained in:
Ottatop 2023-09-20 15:13:03 -05:00
parent ade1a0609b
commit ce96d1d636
4 changed files with 14 additions and 29 deletions

View file

@ -31,17 +31,13 @@ pub struct OutputState {
impl WithState for Output {
type State = OutputState;
fn with_state<F, T>(&self, mut func: F) -> T
fn with_state<F, T>(&self, func: F) -> T
where
F: FnMut(&mut Self::State) -> T,
F: FnOnce(&mut Self::State) -> T,
{
self.user_data()
.insert_if_missing(RefCell::<Self::State>::default);
let state = self
.user_data()
.get::<RefCell<Self::State>>()
.expect("RefCell not in data map");
.get_or_insert(RefCell::<Self::State>::default);
func(&mut state.borrow_mut())
}

View file

@ -584,12 +584,13 @@ impl ApiState {
pub trait WithState {
type State;
/// Access data map state.
///
/// RefCell Safety: This function will panic if called within itself.
fn with_state<F, T>(&self, func: F) -> T
where
F: FnMut(&mut Self::State) -> T;
F: FnOnce(&mut Self::State) -> T;
}
#[derive(Default, Debug)]
@ -600,18 +601,14 @@ pub struct WlSurfaceState {
impl WithState for WlSurface {
type State = WlSurfaceState;
fn with_state<F, T>(&self, mut func: F) -> T
fn with_state<F, T>(&self, func: F) -> T
where
F: FnMut(&mut Self::State) -> T,
F: FnOnce(&mut Self::State) -> T,
{
compositor::with_states(self, |states| {
states
.data_map
.insert_if_missing(RefCell::<Self::State>::default);
let state = states
.data_map
.get::<RefCell<Self::State>>()
.expect("This should never happen");
.get_or_insert(RefCell::<Self::State>::default);
func(&mut state.borrow_mut())
})

View file

@ -551,17 +551,13 @@ impl SpaceElement for WindowElement {
impl WithState for WindowElement {
type State = WindowElementState;
fn with_state<F, T>(&self, mut func: F) -> T
fn with_state<F, T>(&self, func: F) -> T
where
F: FnMut(&mut Self::State) -> T,
F: FnOnce(&mut Self::State) -> T,
{
self.user_data()
.insert_if_missing(RefCell::<Self::State>::default);
let state = self
.user_data()
.get::<RefCell<Self::State>>()
.expect("RefCell not in data map");
.get_or_insert(RefCell::<Self::State>::default);
func(&mut state.borrow_mut())
}

View file

@ -46,17 +46,13 @@ pub struct WindowState {
impl WithState for Window {
type State = WindowState;
fn with_state<F, T>(&self, mut func: F) -> T
fn with_state<F, T>(&self, func: F) -> T
where
F: FnMut(&mut Self::State) -> T,
F: FnOnce(&mut Self::State) -> T,
{
self.user_data()
.insert_if_missing(RefCell::<Self::State>::default);
let state = self
.user_data()
.get::<RefCell<Self::State>>()
.expect("RefCell not in data map");
.get_or_insert(RefCell::<Self::State>::default);
func(&mut state.borrow_mut())
}