use alloc::collections::BTreeMap;
use core::cell::RefCell;
use embassy_sync::blocking_mutex::{Mutex, raw::CriticalSectionRawMutex};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct LayerId(pub u8);
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct LayerManagerEntry(u64);
static LAYER_MANAGER_MAP: Mutex<CriticalSectionRawMutex, RefCell<BTreeMap<u64, LayerId>>> =
Mutex::new(RefCell::new(BTreeMap::new()));
#[derive(Clone, Copy, Default)]
#[non_exhaustive]
pub struct LayerManager {}
impl LayerManager {
pub fn new() -> Self {
Self {}
}
pub fn push(&self, layer: LayerId) -> LayerManagerEntry {
LAYER_MANAGER_MAP.lock(|map| {
let mut map = map.borrow_mut();
let new_id = match map.last_key_value() {
Some((last_id, _)) => last_id + 1,
None => 0,
};
assert!(!map.contains_key(&new_id));
map.insert(new_id, layer);
LayerManagerEntry(new_id)
})
}
pub fn remove(&self, entry: LayerManagerEntry) -> LayerId {
LAYER_MANAGER_MAP.lock(|map| map.borrow_mut().remove(&entry.0).unwrap())
}
pub fn active(&self) -> LayerId {
LAYER_MANAGER_MAP.lock(|map| match map.borrow().last_key_value() {
Some((_, layer)) => *layer,
None => LayerId(0),
})
}
}