use std::collections::HashMap;
use std::collections::hash_map::Entry;
use drmkit_core::Device;
use drmkit_scene::{LayerBufferSource, SourceFormat};
use crate::external::{ExternalDmaBufSource, ExternalError, ExternalPlane};
#[derive(Default)]
pub struct DmaBufSourceCache {
entries: HashMap<u64, ExternalDmaBufSource>,
}
impl DmaBufSourceCache {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn get_or_create(
&mut self,
key: u64,
device: &Device,
format: SourceFormat,
planes: &[ExternalPlane<'_>],
) -> Result<&mut ExternalDmaBufSource, ExternalError> {
let stale = self
.entries
.get(&key)
.is_some_and(|source| LayerBufferSource::format(source) != format);
if stale {
self.entries.remove(&key);
}
match self.entries.entry(key) {
Entry::Occupied(entry) => Ok(entry.into_mut()),
Entry::Vacant(entry) => {
let source = ExternalDmaBufSource::create(device, format, planes, None)?;
Ok(entry.insert(source))
}
}
}
#[must_use]
pub fn find(&self, key: u64) -> Option<&ExternalDmaBufSource> {
self.entries.get(&key)
}
pub fn evict(&mut self, key: u64) -> bool {
self.entries.remove(&key).is_some()
}
pub fn clear(&mut self) {
self.entries.clear();
}
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}