summaryrefslogtreecommitdiffstats
path: root/src/common.rs
diff options
context:
space:
mode:
authorSebastian Thiel <sebastian.thiel@icloud.com>2023-05-02 10:50:20 +0200
committerSebastian Thiel <sebastian.thiel@icloud.com>2023-05-05 12:28:09 +0200
commite03c560e8b54e2e231d578e1d5e9dcd206d34216 (patch)
tree94ffbd2efd24f4b88c8521e4a073c84b338eb6ff /src/common.rs
parentb61ec973b7437230183d6dabf361b0848519f5dc (diff)
generalize the throttle implementation to allow usagein UI
Diffstat (limited to 'src/common.rs')
-rw-r--r--src/common.rs37
1 files changed, 37 insertions, 0 deletions
diff --git a/src/common.rs b/src/common.rs
index 5eb094e..a277c1f 100644
--- a/src/common.rs
+++ b/src/common.rs
@@ -2,6 +2,9 @@ use crate::crossdev;
use crate::traverse::{EntryData, Tree, TreeIndex};
use byte_unit::{n_gb_bytes, n_gib_bytes, n_mb_bytes, n_mib_bytes, ByteUnit};
use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
use std::{fmt, path::Path};
pub fn get_entry_or_panic(tree: &Tree, node_idx: TreeIndex) -> &EntryData {
@@ -114,6 +117,40 @@ pub enum TraversalSorting {
AlphabeticalByFileName,
}
+/// Throttle access to an optional `io::Write` to the specified `Duration`
+#[derive(Debug)]
+pub struct Throttle {
+ trigger: Arc<AtomicBool>,
+}
+
+impl Throttle {
+ pub fn new(duration: Duration) -> Self {
+ let instance = Self {
+ trigger: Default::default(),
+ };
+
+ let trigger = Arc::downgrade(&instance.trigger);
+ std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_secs(1));
+ while let Some(t) = trigger.upgrade() {
+ t.store(true, Ordering::Relaxed);
+ std::thread::sleep(duration);
+ }
+ });
+
+ instance
+ }
+
+ pub fn throttled<F>(&self, f: F)
+ where
+ F: FnOnce(),
+ {
+ if self.trigger.swap(false, Ordering::Relaxed) {
+ f()
+ }
+ }
+}
+
/// Configures a filesystem walk, including output and formatting options.
#[derive(Clone)]
pub struct WalkOptions {