use crate::ids::SfuRid;
pub trait LayerSelector: Send + 'static {
fn select(&self, desired: SfuRid, active: &[SfuRid]) -> SfuRid;
}
#[derive(Debug, Default, Clone, Copy)]
pub struct BestFitSelector;
impl LayerSelector for BestFitSelector {
fn select(&self, desired: SfuRid, active: &[SfuRid]) -> SfuRid {
if active.is_empty() {
return desired;
}
let rank = |r: SfuRid| -> u8 {
if r == SfuRid::LOW {
0
} else if r == SfuRid::MEDIUM {
1
} else {
2
}
};
let desired_rank = rank(desired);
let best_below: Option<SfuRid> = active
.iter()
.copied()
.filter(|&r| rank(r) <= desired_rank)
.max_by_key(|&r| rank(r));
best_below.unwrap_or_else(|| {
active
.iter()
.copied()
.min_by_key(|&r| rank(r))
.unwrap_or(desired)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_active_returns_desired() {
assert_eq!(BestFitSelector.select(SfuRid::MEDIUM, &[]), SfuRid::MEDIUM);
}
#[test]
fn selects_matching_layer() {
let active = [SfuRid::LOW, SfuRid::MEDIUM, SfuRid::HIGH];
assert_eq!(
BestFitSelector.select(SfuRid::MEDIUM, &active),
SfuRid::MEDIUM
);
}
#[test]
fn clamps_to_best_below_desired() {
let active = [SfuRid::LOW, SfuRid::MEDIUM];
assert_eq!(
BestFitSelector.select(SfuRid::HIGH, &active),
SfuRid::MEDIUM
);
}
#[test]
fn falls_back_to_lowest_when_all_above() {
let active = [SfuRid::MEDIUM, SfuRid::HIGH];
assert_eq!(BestFitSelector.select(SfuRid::LOW, &active), SfuRid::MEDIUM);
}
#[test]
fn single_active_rid_always_wins() {
let s = BestFitSelector;
assert_eq!(s.select(SfuRid::LOW, &[SfuRid::HIGH]), SfuRid::HIGH);
assert_eq!(s.select(SfuRid::HIGH, &[SfuRid::LOW]), SfuRid::LOW);
assert_eq!(s.select(SfuRid::MEDIUM, &[SfuRid::MEDIUM]), SfuRid::MEDIUM);
}
#[test]
fn desired_exactly_matches_one_of_multiple_active() {
let s = BestFitSelector;
let active = [SfuRid::LOW, SfuRid::MEDIUM, SfuRid::HIGH];
assert_eq!(s.select(SfuRid::LOW, &active), SfuRid::LOW);
}
#[test]
fn best_fit_prefers_highest_below_desired_not_lowest() {
let s = BestFitSelector;
let active = [SfuRid::LOW, SfuRid::MEDIUM];
let result = s.select(SfuRid::HIGH, &active);
assert_eq!(
result,
SfuRid::MEDIUM,
"BestFitSelector must return the HIGHEST active RID <= desired, not the lowest"
);
}
}