//! The open handles of the databases this device holds beside its own.//!//! A device holds several database files and NEVER attaches one to another://! each is its own connection, opened when something names it — a read, a//! write, the exchange applying its section — and closed again when nothing is//! using it. This is the small set those handles live in.//!//! The device's own (personal) database is not in here: it is the controller's//! attachment, open for as long as the device is connected, because every//! private source writes to it and the connection record lives beside it. A//! SHOWN database — one a window's screens are drawing — is pinned in here, so//! a pass over the others never closes the file a list is reading. The pins//! are a COUNTED SET, one per window showing: two Mac windows may show two//! databases, or the same one, and one window turning away unpins only its//! own.use std::collections::BTreeMap;/// How many databases beside the device's own stay open at once.////// Small on purpose: a handle is a writer, a reader and a page cache each, and/// a phone holding a dozen shared databases is looking at one of them.pub(crate) const OPEN_HANDLES: usize = 3;/// The open handles, least recently used first.pub(crate) structOpenFiles<F> { max: usize, shown: BTreeMap<String, usize>, files: Vec<(String, F)>,}impl<F: Clone> OpenFiles<F> {pub(crate) fn new(max: usize) -> OpenFiles<F> {OpenFiles { max, shown: BTreeMap::new(), files: Vec::new(), } }/// The handle on `database` if it is open, counted as used just now.pub(crate) fn get(&mutself, database: &str) -> Option<F> {let at = self.files.iter().position(|(id, _)| id == database)?;let entry = self.files.remove(at);let file = entry.1.clone();self.files.push(entry);Some(file) }/// Keep a handle just opened, and close the least recently used ones over/// the limit.////// `idle` says whether nothing outside this set still holds the handle. A/// handle in use is never closed from under its user: the set runs over/// its limit for that moment instead, and the next insert tries again./// The handles taken out are handed back for the caller to close. #[must_use = "a closed handle is dropped by the caller, which carries the feeds' index across the close"]pub(crate) fn insert(&mutself, database: &str, file: F, idle: implFn(&F) -> bool) -> Vec<(String, F)> {self.files.retain(|(id, _)| id != database);self.files.push((database.to_string(), file));letmut closed = Vec::new();letmut at = 0;whileself.files.len() > self.max && at < self.files.len() - 1 {let (id, held) = &self.files[at];if !self.shown.contains_key(id) && idle(held) { closed.push(self.files.remove(at)); } else { at += 1; } } closed }/// Pin a database one more window's screens are drawing.pub(crate) fn pin(&mutself, database: &str) { *self.shown.entry(database.to_string()).or_insert(0) += 1; }/// One window stopped drawing `database`: its pin goes, and the database/// stays pinned while another window still shows it. Unpinning what is/// not pinned changes nothing.pub(crate) fn unpin(&mutself, database: &str) {ifletSome(count) = self.shown.get_mut(database) { *count -= 1;if *count == 0 {self.shown.remove(database); } } }/// The pinned databases, in id order.pub(crate) fn shown(&self) -> Vec<String> {self.shown.keys().cloned().collect() }/// Close every handle nothing is using, the shown ones excepted. The/// handles taken out are handed back for the caller to close. #[must_use = "a closed handle is dropped by the caller, which carries the feeds' index across the close"]pub(crate) fn close_idle(&mutself, idle: implFn(&F) -> bool) -> Vec<(String, F)> {let (closed, kept) = std::mem::take(&mutself.files) .into_iter() .partition(|(id, held)| !self.shown.contains_key(id) && idle(held));self.files = kept; closed }/// Close one database's handle and drop its pins — its file is going.pub(crate) fn close(&mutself, database: &str) {self.files.retain(|(id, _)| id != database);self.shown.remove(database); }/// Close everything and forget what was shown — the device left.pub(crate) fn clear(&mutself) {self.files.clear();self.shown.clear(); }/// The databases open right now, least recently used first.pub(crate) fn open_ids(&self) -> Vec<String> {self.files.iter().map(|(id, _)| id.clone()).collect() }}#[cfg(test)]mod tests {usesuper::OpenFiles;fn ids(files: &OpenFiles<u8>) -> Vec<String> { files.open_ids() } #[test]fn the_least_recently_used_idle_handle_closes_over_the_limit() {letmut files = OpenFiles::new(2);let _ = files.insert("a", 1, |_| true);let _ = files.insert("b", 2, |_| true); assert_eq!(files.get("a"), Some(1));let _ = files.insert("c", 3, |_| true); assert_eq!(ids(&files), ["a", "c"]); } #[test]fn the_shown_database_and_a_handle_in_use_are_never_closed() {letmut files = OpenFiles::new(1);let _ = files.insert("shown", 1, |_| true); files.pin("shown");let _ = files.insert("busy", 2, |_| true);// `busy` is in use (not idle), `shown` is pinned: both outlive the// limit, and only the newcomer's turn can end.let _ = files.insert("c", 3, |file| *file != 2); assert_eq!(ids(&files), ["shown", "busy", "c"]);let _ = files.close_idle(|_| true); assert_eq!(ids(&files), ["shown"]); files.clear(); assert!(ids(&files).is_empty()); assert!(files.shown().is_empty()); } #[test]fn two_windows_pin_one_database_and_one_turning_away_leaves_it_pinned() {letmut files = OpenFiles::new(1); files.pin("family"); files.pin("family"); files.pin("team");let _ = files.insert("family", 1, |_| true);let _ = files.insert("team", 2, |_| true); files.unpin("family");let _ = files.close_idle(|_| true); assert_eq!(ids(&files), ["family", "team"]); files.unpin("family"); files.unpin("family");let _ = files.close_idle(|_| true); assert_eq!(ids(&files), ["team"]); assert_eq!(files.shown(), ["team"]); }}