atomic-time 0.2.1

Lock-free, thread-safe atomic versions of Duration, SystemTime, Instant and their Option variants
Documentation
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
use std::time::Instant;

use super::*;

/// Atomic version of [`Option<Instant>`].
#[repr(transparent)]
pub struct AtomicOptionInstant(AtomicOptionDuration);

impl core::fmt::Debug for AtomicOptionInstant {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_tuple("AtomicOptionInstant")
      .field(&self.load(Ordering::SeqCst))
      .finish()
  }
}
impl Default for AtomicOptionInstant {
  /// Equivalent to `Option::<Instant>::None`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  fn default() -> Self {
    Self::none()
  }
}
impl From<Option<Instant>> for AtomicOptionInstant {
  #[cfg_attr(not(tarpaulin), inline(always))]
  fn from(instant: Option<Instant>) -> Self {
    Self::new(instant)
  }
}

impl AtomicOptionInstant {
  /// Equivalent to atomic version `Option::<Instant>::None`.
  ///
  /// # Examples
  ///
  /// ```rust
  /// use atomic_time::AtomicOptionInstant;
  ///
  /// let none = AtomicOptionInstant::none();
  /// assert_eq!(none.load(std::sync::atomic::Ordering::SeqCst), None);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn none() -> Self {
    Self(AtomicOptionDuration::new(None))
  }

  /// Returns the instant corresponding to "now".
  ///
  /// # Examples
  /// ```
  /// use atomic_time::AtomicOptionInstant;
  ///
  /// let now = AtomicOptionInstant::now();
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn now() -> Self {
    Self::new(Some(Instant::now()))
  }

  /// Creates a new `AtomicOptionInstant` with the given `Instant` value.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn new(instant: Option<Instant>) -> Self {
    Self(AtomicOptionDuration::new(
      instant.map(encode_instant_to_duration),
    ))
  }

  /// Loads a value from the atomic instant.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn load(&self, order: Ordering) -> Option<Instant> {
    self.0.load(order).map(decode_instant_from_duration)
  }

  /// Stores a value into the atomic instant.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn store(&self, instant: Option<Instant>, order: Ordering) {
    self.0.store(instant.map(encode_instant_to_duration), order)
  }

  /// Stores a value into the atomic instant, returning the previous value.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn swap(&self, instant: Option<Instant>, order: Ordering) -> Option<Instant> {
    self
      .0
      .swap(instant.map(encode_instant_to_duration), order)
      .map(decode_instant_from_duration)
  }

  /// Stores a value into the atomic instant if the current value is the same as the `current`
  /// value.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn compare_exchange(
    &self,
    current: Option<Instant>,
    new: Option<Instant>,
    success: Ordering,
    failure: Ordering,
  ) -> Result<Option<Instant>, Option<Instant>> {
    match self.0.compare_exchange(
      current.map(encode_instant_to_duration),
      new.map(encode_instant_to_duration),
      success,
      failure,
    ) {
      Ok(duration) => Ok(duration.map(decode_instant_from_duration)),
      Err(duration) => Err(duration.map(decode_instant_from_duration)),
    }
  }

  /// Stores a value into the atomic instant if the current value is the same as the `current`
  /// value.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn compare_exchange_weak(
    &self,
    current: Option<Instant>,
    new: Option<Instant>,
    success: Ordering,
    failure: Ordering,
  ) -> Result<Option<Instant>, Option<Instant>> {
    match self.0.compare_exchange_weak(
      current.map(encode_instant_to_duration),
      new.map(encode_instant_to_duration),
      success,
      failure,
    ) {
      Ok(duration) => Ok(duration.map(decode_instant_from_duration)),
      Err(duration) => Err(duration.map(decode_instant_from_duration)),
    }
  }

  /// 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 atomic_time::AtomicOptionInstant;
  /// use std::{time::{Duration, Instant}, sync::atomic::Ordering};
  ///
  /// let now = Instant::now();
  /// let x = AtomicOptionInstant::none();
  /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(None));
  /// x.store(Some(now), Ordering::SeqCst);
  /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x.map(|val| val + Duration::from_secs(1)))), Ok(Some(now)));
  /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x.map(|val| val + Duration::from_secs(1)))), Ok(Some(now + Duration::from_secs(1))));
  /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x.map(|val| val + Duration::from_secs(1)))), Ok(Some(now + Duration::from_secs(2))));
  /// assert_eq!(x.load(Ordering::SeqCst), Some(now + Duration::from_secs(3)));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn fetch_update<F>(
    &self,
    set_order: Ordering,
    fetch_order: Ordering,
    mut f: F,
  ) -> Result<Option<Instant>, Option<Instant>>
  where
    F: FnMut(Option<Instant>) -> Option<Option<Instant>>,
  {
    self
      .0
      .fetch_update(set_order, fetch_order, |duration| {
        f(duration.map(decode_instant_from_duration))
          .map(|system_time| system_time.map(encode_instant_to_duration))
      })
      .map(|duration| duration.map(decode_instant_from_duration))
      .map_err(|duration| duration.map(decode_instant_from_duration))
  }

  /// Returns `true` if operations on values of this type are lock-free.
  /// If the compiler or the platform doesn't support the necessary
  /// atomic instructions, global locks for every potentially
  /// concurrent atomic operation will be used.
  ///
  /// # Examples
  /// ```
  /// use atomic_time::AtomicOptionInstant;
  ///
  /// let is_lock_free = AtomicOptionInstant::is_lock_free();
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn is_lock_free() -> bool {
    AtomicU128::is_lock_free()
  }

  /// 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.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_inner(self) -> Option<Instant> {
    self.0.into_inner().map(decode_instant_from_duration)
  }
}

#[cfg(feature = "serde")]
const _: () = {
  use core::time::Duration;
  use serde::{Deserialize, Serialize};

  impl Serialize for AtomicOptionInstant {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
      self.0.load(Ordering::SeqCst).serialize(serializer)
    }
  }

  impl<'de> Deserialize<'de> for AtomicOptionInstant {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
      Ok(Self::new(
        Option::<Duration>::deserialize(deserializer)?.map(decode_instant_from_duration),
      ))
    }
  }
};

#[cfg(test)]
mod tests {
  use super::*;
  use std::time::Duration;

  #[test]
  fn test_atomic_option_instant_none() {
    let atomic_instant = AtomicOptionInstant::none();
    assert_eq!(atomic_instant.load(Ordering::SeqCst), None);
  }

  #[test]
  fn test_atomic_option_instant_now() {
    let atomic_instant = AtomicOptionInstant::now();
    let now = Instant::now();
    if let Some(loaded_instant) = atomic_instant.load(Ordering::SeqCst) {
      assert!(loaded_instant <= now);
      assert!(loaded_instant >= now - Duration::from_secs(1));
    } else {
      panic!("AtomicOptionInstant::now() should not be None");
    }
  }

  #[test]
  fn test_atomic_option_instant_new_and_load() {
    let now = Some(Instant::now());
    let atomic_instant = AtomicOptionInstant::new(now);
    assert_eq!(atomic_instant.load(Ordering::SeqCst), now);
  }

  #[test]
  fn test_atomic_option_instant_store_and_load() {
    let now = Some(Instant::now());
    let after_one_sec = now.map(|t| t + Duration::from_secs(1));
    let atomic_instant = AtomicOptionInstant::new(now);
    atomic_instant.store(after_one_sec, Ordering::SeqCst);
    assert_eq!(atomic_instant.load(Ordering::SeqCst), after_one_sec);
  }

  #[test]
  fn test_atomic_option_instant_swap() {
    let now = Some(Instant::now());
    let after_one_sec = now.map(|t| t + Duration::from_secs(1));
    let atomic_instant = AtomicOptionInstant::new(now);
    let prev_instant = atomic_instant.swap(after_one_sec, Ordering::SeqCst);
    assert_eq!(prev_instant, now);
    assert_eq!(atomic_instant.load(Ordering::SeqCst), after_one_sec);
  }

  #[test]
  fn test_atomic_option_instant_compare_exchange() {
    let now = Some(Instant::now());
    let after_one_sec = now.map(|t| t + Duration::from_secs(1));
    let atomic_instant = AtomicOptionInstant::new(now);
    let result =
      atomic_instant.compare_exchange(now, after_one_sec, Ordering::SeqCst, Ordering::SeqCst);
    assert!(result.is_ok());
    assert_eq!(atomic_instant.load(Ordering::SeqCst), after_one_sec);
  }

  #[test]
  fn test_atomic_option_instant_compare_exchange_weak() {
    let now = Some(Instant::now());
    let after_one_sec = now.map(|t| t + Duration::from_secs(1));
    let atomic_instant = AtomicOptionInstant::new(now);

    let mut result;
    loop {
      result = atomic_instant.compare_exchange_weak(
        now,
        after_one_sec,
        Ordering::SeqCst,
        Ordering::SeqCst,
      );
      if result.is_ok() {
        break;
      }
    }
    assert!(result.is_ok());
    assert_eq!(atomic_instant.load(Ordering::SeqCst), after_one_sec);
  }

  #[test]
  fn test_atomic_option_instant_fetch_update() {
    let now = Some(Instant::now());
    let atomic_instant = AtomicOptionInstant::new(now);

    let result = atomic_instant.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |prev| {
      Some(prev.map(|t| t + Duration::from_secs(1)))
    });
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), now);
    assert_eq!(
      atomic_instant.load(Ordering::SeqCst),
      now.map(|t| t + Duration::from_secs(1))
    );
  }

  #[test]
  fn test_atomic_option_instant_thread_safety() {
    use std::sync::Arc;
    use std::thread;

    // Fixed starting value + CAS loop = exact final result. The
    // earlier implementation did `load + add + store` (not a CAS) and
    // asserted "within 4 seconds of now", which even a single
    // surviving write would satisfy.
    let start = Instant::now();
    let atomic_time = Arc::new(AtomicOptionInstant::new(Some(start)));
    let mut handles = vec![];

    for _ in 0..4 {
      let atomic_clone = Arc::clone(&atomic_time);
      let handle = thread::spawn(move || {
        atomic_clone
          .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
            current.map(|t| Some(t + Duration::from_secs(1)))
          })
          .expect("atomic is always Some in this test");
      });
      handles.push(handle);
    }

    for handle in handles {
      handle.join().unwrap();
    }

    // 4 threads × 1 second = 4 seconds, no lost updates.
    assert_eq!(
      atomic_time.load(Ordering::SeqCst),
      Some(start + Duration::from_secs(4))
    );
  }

  #[test]
  fn test_atomic_option_instant_debug() {
    let atomic_instant = AtomicOptionInstant::now();
    let debug_str = format!("{:?}", atomic_instant);
    assert!(debug_str.contains("AtomicOptionInstant"));
  }

  #[test]
  fn test_atomic_option_instant_default() {
    let atomic_instant = AtomicOptionInstant::default();
    assert_eq!(atomic_instant.load(Ordering::SeqCst), None);
  }

  #[test]
  fn test_atomic_option_instant_from() {
    let now = Some(Instant::now());
    let atomic_instant = AtomicOptionInstant::from(now);
    assert_eq!(atomic_instant.load(Ordering::SeqCst), now);
  }

  #[test]
  fn test_atomic_option_instant_from_none() {
    let atomic_instant = AtomicOptionInstant::from(None);
    assert_eq!(atomic_instant.load(Ordering::SeqCst), None);
  }

  #[test]
  fn test_atomic_option_instant_into_inner() {
    let now = Some(Instant::now());
    let atomic_instant = AtomicOptionInstant::new(now);
    assert_eq!(atomic_instant.into_inner(), now);
  }

  #[test]
  fn test_atomic_option_instant_into_inner_none() {
    let atomic_instant = AtomicOptionInstant::none();
    assert_eq!(atomic_instant.into_inner(), None);
  }

  #[test]
  fn test_atomic_option_instant_compare_exchange_failure() {
    let now = Some(Instant::now());
    let other = now.map(|t| t + Duration::from_secs(5));
    let atomic_instant = AtomicOptionInstant::new(now);
    let result = atomic_instant.compare_exchange(other, other, Ordering::SeqCst, Ordering::SeqCst);
    assert!(result.is_err());
    assert_eq!(result.unwrap_err(), now);
  }

  #[test]
  fn test_atomic_option_instant_compare_exchange_weak_failure() {
    let now = Some(Instant::now());
    let other = now.map(|t| t + Duration::from_secs(5));
    let atomic_instant = AtomicOptionInstant::new(now);
    let result =
      atomic_instant.compare_exchange_weak(other, other, Ordering::SeqCst, Ordering::SeqCst);
    assert!(result.is_err());
  }

  #[test]
  fn test_atomic_option_instant_fetch_update_failure() {
    let now = Some(Instant::now());
    let atomic_instant = AtomicOptionInstant::new(now);
    let result = atomic_instant.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None);
    assert!(result.is_err());
    assert_eq!(result.unwrap_err(), now);
  }

  #[cfg(feature = "serde")]
  #[test]
  fn test_atomic_option_instant_serde() {
    use serde::{Deserialize, Serialize};

    #[derive(Serialize, Deserialize)]
    struct Test {
      time: AtomicOptionInstant,
    }

    let now = Instant::now();
    let test = Test {
      time: AtomicOptionInstant::new(Some(now)),
    };
    let serialized = serde_json::to_string(&test).unwrap();
    let deserialized: Test = serde_json::from_str(&serialized).unwrap();
    assert_eq!(deserialized.time.load(Ordering::SeqCst), Some(now));
  }

  #[test]
  fn decode_option_instant_from_extreme_duration_does_not_panic() {
    let max_dur = Duration::new(u64::MAX, 999_999_999);
    let decoded = crate::utils::decode_instant_from_duration(max_dur);
    // Must not panic — the value saturates at `instant_now`.
    let _ = decoded;
  }

  #[cfg(feature = "serde")]
  #[test]
  fn deserialize_extreme_option_instant_does_not_panic() {
    // Simulates adversarial input through serde. The inner Duration
    // is so large that decoding it into an Instant would overflow —
    // the deserialized value must be `Ok(Some(_))`, not a panic.
    let json = r#"{"secs":18446744073709551615,"nanos":999999999}"#;
    let result: Result<AtomicOptionInstant, _> = serde_json::from_str(json);
    assert!(
      result.is_ok(),
      "deserialization of extreme Option<Instant> should not panic"
    );
    assert!(result.unwrap().load(Ordering::SeqCst).is_some());
  }
}