Skip to main content

fs_core/
time.rs

1#[cfg(not(feature = "std"))]
2use core::cell::RefCell;
3
4#[cfg(feature = "std")]
5use std::sync::atomic::{AtomicU64, Ordering};
6
7pub trait TimeProvider {
8    fn now(&self) -> u64;
9}
10
11/// A simple monotonic counter for timestamps.
12///
13/// For std builds, uses `AtomicU64` for thread safety.
14/// For no_std builds, uses `RefCell<u64>`.
15pub struct MonotonicCounter {
16    #[cfg(feature = "std")]
17    counter: AtomicU64,
18    #[cfg(not(feature = "std"))]
19    counter: RefCell<u64>,
20}
21
22impl Default for MonotonicCounter {
23    fn default() -> Self {
24        Self::new()
25    }
26}
27
28impl MonotonicCounter {
29    #[cfg(feature = "std")]
30    pub fn new() -> Self {
31        Self {
32            counter: AtomicU64::new(0),
33        }
34    }
35
36    #[cfg(not(feature = "std"))]
37    pub fn new() -> Self {
38        Self {
39            counter: RefCell::new(0),
40        }
41    }
42}
43
44impl TimeProvider for MonotonicCounter {
45    #[cfg(feature = "std")]
46    fn now(&self) -> u64 {
47        self.counter.fetch_add(1, Ordering::Relaxed)
48    }
49
50    #[cfg(not(feature = "std"))]
51    fn now(&self) -> u64 {
52        let mut counter = self.counter.borrow_mut();
53        let val = *counter;
54        *counter = val + 1;
55        val
56    }
57}