1 /// Handles dynamic thread sleep time.
2 pub struct SleepAmountTracker {
3     /// The maximum amount of time for thread to sleep.
4     max_time_to_sleep: u8,
5     /// Current time to block the thread.
6     time_to_sleep: u8,
7     /// The current warm wakeup number.
8     warm_wakeup: u8,
9     /// The maximum amount of clipboard wakeups in a row with low sleep amount.
10     max_warm_wakeups: u8,
11 }
12 
13 impl SleepAmountTracker {
14     /// Build new tracker for sleep amount.
15     ///
16     /// `max_time_to_sleep` - maximum sleep value for a thread.
17     /// ``
new(max_time_to_sleep: u8, max_warm_wakeups: u8) -> Self18     pub fn new(max_time_to_sleep: u8, max_warm_wakeups: u8) -> Self {
19         Self { max_time_to_sleep, max_warm_wakeups, warm_wakeup: 0, time_to_sleep: 0 }
20     }
21 
22     /// Reset the current sleep amount to 0ms.
23     #[inline]
reset_sleep(&mut self)24     pub fn reset_sleep(&mut self) {
25         self.time_to_sleep = 0;
26     }
27 
28     /// Adjust the sleep amount.
29     #[inline]
increase_sleep(&mut self)30     pub fn increase_sleep(&mut self) {
31         if self.time_to_sleep == 0 {
32             // Reset `time_to_sleep` to one, so we can reach `max_time_to_sleep`.
33             self.time_to_sleep = 1;
34             // Reset `warm_wakeup` count.
35             self.warm_wakeup = 0;
36 
37             return;
38         }
39 
40         if self.warm_wakeup < self.max_warm_wakeups {
41             // Handled warm wake up.
42             self.warm_wakeup += 1;
43         } else if self.time_to_sleep < self.max_warm_wakeups {
44             // The aim of this different sleep times is to provide a good performance under
45             // high the load and not waste system resources too much when idle.
46             self.time_to_sleep = std::cmp::min(2 * self.time_to_sleep, self.max_time_to_sleep);
47         }
48     }
49 
50     /// Get the current time to sleep in ms.
51     #[inline]
sleep_amount(&self) -> u852     pub fn sleep_amount(&self) -> u8 {
53         self.time_to_sleep
54     }
55 }
56