#[allow(dead_code)]
pub struct CachedDisconnection {
cached: bool,
}
impl CachedDisconnection {
#[inline]
#[allow(dead_code)]
pub const fn new() -> Self {
Self { cached: false }
}
#[inline]
#[allow(dead_code)]
pub fn check<F>(&mut self, check_fn: F) -> bool
where
F: FnOnce() -> bool,
{
if self.cached {
return true;
}
let disconnected = check_fn();
if disconnected {
self.cached = true;
}
disconnected
}
}
impl Default for CachedDisconnection {
#[allow(dead_code)]
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
#[allow(dead_code)]
mod tests {
use super::*;
#[test]
fn test_cached_disconnection_initially_false() {
let mut cached = CachedDisconnection::new();
let result = cached.check(|| false);
assert!(!result);
}
#[test]
fn test_cached_disconnection_caches_true() {
let mut cached = CachedDisconnection::new();
let mut call_count = 0;
let result = cached.check(|| {
call_count += 1;
true
});
assert!(result);
assert_eq!(call_count, 1);
let result = cached.check(|| {
call_count += 1;
false });
assert!(result); assert_eq!(call_count, 1); }
#[test]
fn test_cached_disconnection_multiple_false() {
let mut cached = CachedDisconnection::new();
let mut call_count = 0;
for _ in 0..5 {
let result = cached.check(|| {
call_count += 1;
false
});
assert!(!result);
}
assert_eq!(call_count, 5); }
#[test]
fn test_default() {
let mut cached = CachedDisconnection::default();
let result = cached.check(|| false);
assert!(!result);
}
}