use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{LazyLock, Mutex},
};
use super::policy::AcpProtocol;
pub(crate) static ADAPTERS: LazyLock<Adapters> = LazyLock::new(Adapters::default);
#[derive(Default)]
pub(crate) struct Adapters(Mutex<HashMap<PathBuf, Learned>>);
#[derive(Clone, Debug, Default)]
struct Learned {
v1_only_at: Option<Option<String>>,
said: Option<AdapterFacts>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct AdapterFacts {
pub(crate) protocol: AcpProtocol,
pub(crate) images: bool,
}
impl Adapters {
pub(crate) fn known(&self, path: &Path) -> Option<AdapterFacts> {
self.lock().get(path)?.said
}
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<PathBuf, Learned>> {
self.0.lock().expect("ACP adapters")
}
}
#[derive(Clone, Copy)]
pub(super) struct Adapter<'a> {
pub(super) cache: &'a Adapters,
pub(super) path: &'a Path,
}
impl Adapter<'_> {
pub(super) fn start_on(self, asked: AcpProtocol) -> AcpProtocol {
let v1_only = self
.cache
.lock()
.get(self.path)
.is_some_and(|learned| learned.v1_only_at.is_some());
match asked {
AcpProtocol::V2 if v1_only => AcpProtocol::V1,
asked => asked,
}
}
pub(super) fn initialized(
self,
requested: AcpProtocol,
protocol: AcpProtocol,
version: Option<String>,
images: bool,
) {
let mut adapters = self.cache.lock();
let learned = adapters.entry(self.path.to_owned()).or_default();
learned.v1_only_at = match (requested, protocol, learned.v1_only_at.take()) {
(AcpProtocol::V2, AcpProtocol::V1, _) => Some(version),
(_, AcpProtocol::V1, Some(at)) if at == version => Some(at),
_ => None,
};
learned.said = Some(AdapterFacts { protocol, images });
}
pub(super) fn v1_failed(self) {
if let Some(learned) = self.cache.lock().get_mut(self.path) {
learned.v1_only_at = None;
}
}
}
#[cfg(test)]
#[path = "adapters_tests.rs"]
mod tests;