use std::collections::HashMap;
use shep_client::shep_core::protocol::ProcessInfo;
#[derive(Debug, Clone, Default)]
pub struct Names {
by_id: HashMap<u32, String>,
}
impl Names {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn refresh(&mut self, roll: &[ProcessInfo]) {
self.by_id = roll
.iter()
.map(|info| (info.id, info.name.clone()))
.collect();
}
#[must_use]
pub fn get(&self, id: u32) -> String {
self.by_id
.get(&id)
.cloned()
.unwrap_or_else(|| format!("sheep {id}"))
}
}
#[cfg(test)]
mod tests {
use shep_client::shep_core::{protocol::ProcessInfo, status::ProcStatus};
use super::Names;
fn info(id: u32, name: &str) -> ProcessInfo {
ProcessInfo::builder(id, name, ProcStatus::Online).build()
}
#[test]
fn an_unknown_id_is_named_rather_than_dropped() {
let names = Names::new();
assert_eq!(
names.get(7),
"sheep 7",
"a line from a sheep the cache has not seen is still a line worth showing"
);
}
#[test]
fn a_refresh_replaces_rather_than_merges() {
let mut names = Names::new();
names.refresh(&[info(1, "web"), info(2, "api")]);
names.refresh(&[info(1, "web")]);
assert_eq!(names.get(1), "web");
assert_eq!(names.get(2), "sheep 2");
}
}