1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
use core::{sync::atomic::Ordering, time::Duration as StdDuration};
use atomic::Atomic;
/// Atomic duration
#[derive(Debug)]
#[repr(transparent)]
pub struct AtomicDuration(Atomic<Duration>);
impl AtomicDuration {
/// Creates a new `AtomicDuration` with the given value.
pub const fn new(duration: StdDuration) -> Self {
Self(Atomic::new(Duration::from_std(duration)))
}
/// Loads [`Duration`](StdDuration) from `AtomicDuration`.
///
/// load takes an [`Ordering`] argument which describes the memory ordering of this operation.
///
/// # Panics
/// Panics if order is [`Release`](Ordering::Release) or [`AcqRel`](Ordering::AcqRel).
pub fn load(&self, ordering: Ordering) -> StdDuration {
self.0.load(ordering).to_std()
}
/// Stores a value into the `AtomicDuration`.
///
/// `store` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation.
///
/// # Panics
///
/// Panics if `order` is [`Acquire`](Ordering::Acquire) or [`AcqRel`](Ordering::AcqRel).
pub fn store(&self, val: StdDuration, ordering: Ordering) {
self.0.store(Duration::from_std(val), ordering)
}
/// Stores a value into the `AtomicDuration`, returning the old value.
///
/// `swap` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation.
pub fn swap(&self, val: StdDuration, ordering: Ordering) -> StdDuration {
self.0.swap(Duration::from_std(val), ordering).to_std()
}
/// Stores a value into the `AtomicDuration` if the current value is the same as the
/// `current` value.
///
/// Unlike [`compare_exchange`], this function is allowed to spuriously fail
/// even when the comparison succeeds, which can result in more efficient
/// code on some platforms. The return value is a result indicating whether
/// the new value was written and containing the previous value.
///
/// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. The first describes the required ordering if
/// the operation succeeds while the second describes the required ordering
/// when the operation fails. The failure ordering can't be [`Release`](Ordering::Release) or
/// [`AcqRel`](Ordering::AcqRel) and must be equivalent or weaker than the success ordering.
/// success ordering.
///
/// [`compare_exchange`]: #method.compare_exchange
pub fn compare_exchange_weak(
&self,
current: StdDuration,
new: StdDuration,
success: Ordering,
failure: Ordering,
) -> Result<StdDuration, StdDuration> {
self
.0
.compare_exchange_weak(
Duration::from_std(current),
Duration::from_std(new),
success,
failure,
)
.map(|d| d.to_std())
.map_err(|d| d.to_std())
}
/// Stores a value into the `AtomicDuration` if the current value is the same as the
/// `current` value.
///
/// The return value is a result indicating whether the new value was
/// written and containing the previous value. On success this value is
/// guaranteed to be equal to `new`.
///
/// [`compare_exchange`] takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. The first describes the required ordering if
/// the operation succeeds while the second describes the required ordering
/// when the operation fails. The failure ordering can't be [`Release`](Ordering::Release) or
/// [`AcqRel`](Ordering::AcqRel) and must be equivalent or weaker than the success ordering.
///
/// [`compare_exchange`]: #method.compare_exchange
pub fn compare_exchange(
&self,
current: StdDuration,
new: StdDuration,
success: Ordering,
failure: Ordering,
) -> Result<StdDuration, StdDuration> {
self
.0
.compare_exchange(
Duration::from_std(current),
Duration::from_std(new),
success,
failure,
)
.map(|d| d.to_std())
.map_err(|d| d.to_std())
}
/// Fetches the value, and applies a function to it that returns an optional
/// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
/// `Err(previous_value)`.
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
/// only once to the stored value.
///
/// `fetch_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
/// [`compare_exchange`] respectively.
///
/// Using [`Acquire`](Ordering::Acquire) as success ordering makes the store part
/// of this operation [`Relaxed`](Ordering::Relaxed), and using [`Release`](Ordering::Release) makes the final successful load
/// [`Relaxed`](Ordering::Relaxed). The (failed) load ordering can only be [`SeqCst`](Ordering::SeqCst), [`Acquire`](Ordering::Acquire) or [`Relaxed`](Ordering::Release)
/// and must be equivalent to or weaker than the success ordering.
///
/// [`compare_exchange`]: #method.compare_exchange
///
/// # Examples
///
/// ```rust
/// use ruraft_utils::atomic_duration::AtomicDuration;
/// use std::{time::Duration, sync::atomic::Ordering};
///
/// let x = AtomicDuration::new(Duration::from_secs(7));
/// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(Duration::from_secs(7)));
/// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + Duration::from_secs(1))), Ok(Duration::from_secs(7)));
/// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + Duration::from_secs(1))), Ok(Duration::from_secs(8)));
/// assert_eq!(x.load(Ordering::SeqCst), Duration::from_secs(9));
/// ```
pub fn fetch_update<F>(
&self,
set_order: Ordering,
fetch_order: Ordering,
mut f: F,
) -> Result<StdDuration, StdDuration>
where
F: FnMut(StdDuration) -> Option<StdDuration>,
{
self
.0
.fetch_update(set_order, fetch_order, |d| {
f(d.to_std()).map(Duration::from_std)
})
.map(|d| d.to_std())
.map_err(|d| d.to_std())
}
/// Consumes the atomic and returns the contained value.
///
/// This is safe because passing `self` by value guarantees that no other threads are
/// concurrently accessing the atomic data.
#[inline]
pub fn into_inner(self) -> StdDuration {
self.0.into_inner().to_std()
}
}
#[cfg(feature = "serde")]
const _: () = {
use serde::{Deserialize, Serialize};
impl Serialize for AtomicDuration {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.load(Ordering::SeqCst).serialize(serializer)
}
}
impl<'de> Deserialize<'de> for AtomicDuration {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(Self::new(StdDuration::deserialize(deserializer)?))
}
}
};
/// A duration type that does not contain any padding bytes
#[derive(bytemuck::NoUninit, PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)]
#[repr(transparent)]
struct Duration(u64);
impl Duration {
const fn from_std(d: StdDuration) -> Self {
Self(d.as_millis() as u64)
}
const fn to_std(self) -> StdDuration {
StdDuration::from_millis(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::Ordering;
use std::time::Duration;
#[test]
fn test_atomic_duration_new() {
let duration = Duration::from_secs(5);
let atomic_duration = AtomicDuration::new(duration);
assert_eq!(atomic_duration.load(Ordering::SeqCst), duration);
}
#[test]
fn test_atomic_duration_load() {
let duration = Duration::from_secs(10);
let atomic_duration = AtomicDuration::new(duration);
assert_eq!(atomic_duration.load(Ordering::SeqCst), duration);
}
#[test]
fn test_atomic_duration_store() {
let initial_duration = Duration::from_secs(3);
let new_duration = Duration::from_secs(7);
let atomic_duration = AtomicDuration::new(initial_duration);
atomic_duration.store(new_duration, Ordering::SeqCst);
assert_eq!(atomic_duration.load(Ordering::SeqCst), new_duration);
}
#[test]
fn test_atomic_duration_swap() {
let initial_duration = Duration::from_secs(2);
let new_duration = Duration::from_secs(8);
let atomic_duration = AtomicDuration::new(initial_duration);
let prev_duration = atomic_duration.swap(new_duration, Ordering::SeqCst);
assert_eq!(prev_duration, initial_duration);
assert_eq!(atomic_duration.load(Ordering::SeqCst), new_duration);
}
#[test]
fn test_atomic_duration_compare_exchange_weak() {
let initial_duration = Duration::from_secs(4);
let atomic_duration = AtomicDuration::new(initial_duration);
// Successful exchange
let result = atomic_duration.compare_exchange_weak(
initial_duration,
Duration::from_secs(6),
Ordering::SeqCst,
Ordering::SeqCst,
);
assert!(result.is_ok());
assert_eq!(result.unwrap(), initial_duration);
assert_eq!(
atomic_duration.load(Ordering::SeqCst),
Duration::from_secs(6)
);
// Failed exchange
let result = atomic_duration.compare_exchange_weak(
initial_duration,
Duration::from_secs(7),
Ordering::SeqCst,
Ordering::SeqCst,
);
assert!(result.is_err());
assert_eq!(result.unwrap_err(), Duration::from_secs(6));
}
#[test]
fn test_atomic_duration_compare_exchange() {
let initial_duration = Duration::from_secs(1);
let atomic_duration = AtomicDuration::new(initial_duration);
// Successful exchange
let result = atomic_duration.compare_exchange(
initial_duration,
Duration::from_secs(5),
Ordering::SeqCst,
Ordering::SeqCst,
);
assert!(result.is_ok());
assert_eq!(result.unwrap(), initial_duration);
assert_eq!(
atomic_duration.load(Ordering::SeqCst),
Duration::from_secs(5)
);
// Failed exchange
let result = atomic_duration.compare_exchange(
initial_duration,
Duration::from_secs(6),
Ordering::SeqCst,
Ordering::SeqCst,
);
assert!(result.is_err());
assert_eq!(result.unwrap_err(), Duration::from_secs(5));
}
#[test]
fn test_atomic_duration_fetch_update() {
let initial_duration = Duration::from_secs(4);
let atomic_duration = AtomicDuration::new(initial_duration);
let result = atomic_duration.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |d| {
Some(d + Duration::from_secs(2))
});
assert_eq!(result, Ok(initial_duration));
assert_eq!(
atomic_duration.load(Ordering::SeqCst),
Duration::from_secs(6)
);
}
#[test]
fn test_atomic_duration_into_inner() {
let duration = Duration::from_secs(3);
let atomic_duration = AtomicDuration::new(duration);
assert_eq!(atomic_duration.into_inner(), duration);
}
#[test]
#[cfg(feature = "std")]
fn test_atomic_duration_thread_safety() {
use std::sync::Arc;
use std::thread;
let atomic_duration = Arc::new(AtomicDuration::new(Duration::from_secs(0)));
let mut handles = vec![];
// Spawn multiple threads to increment the duration
for _ in 0..10 {
let atomic_clone = Arc::clone(&atomic_duration);
let handle = thread::spawn(move || {
for _ in 0..100 {
loop {
let current = atomic_clone.load(Ordering::SeqCst);
let new = current + Duration::from_millis(1);
match atomic_clone.compare_exchange_weak(
current,
new,
Ordering::SeqCst,
Ordering::SeqCst,
) {
Ok(_) => break, // Successfully updated
Err(_) => continue, // Spurious failure, try again
}
}
}
});
handles.push(handle);
}
// Wait for all threads to complete
for handle in handles {
handle.join().unwrap();
}
// Verify the final value
let expected_duration = Duration::from_millis(10 * 100);
assert_eq!(atomic_duration.load(Ordering::SeqCst), expected_duration);
}
#[cfg(feature = "serde")]
#[test]
fn test_atomic_duration_serde() {
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Test {
duration: AtomicDuration,
}
let test = Test {
duration: AtomicDuration::new(Duration::from_secs(5)),
};
let serialized = serde_json::to_string(&test).unwrap();
let deserialized: Test = serde_json::from_str(&serialized).unwrap();
assert_eq!(
deserialized.duration.load(Ordering::SeqCst),
Duration::from_secs(5)
);
}
}