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
use std::{
sync::atomic::{AtomicUsize, Ordering},
time::{Duration, Instant},
};
pub mod duration;
#[cfg(feature = "usize")]
pub mod usize;
#[derive(Debug)]
pub struct AtomicInstant {
pub(crate) base: Instant,
pub(crate) offset_nanos: AtomicUsize,
}
impl AtomicInstant {
fn instant_from_offset_nanos(&self, offset_nanos: usize) -> Instant {
self.base + Duration::from_nanos(offset_nanos as u64)
}
// Implicitly cannot go backwards
fn offset_nanos_from_instant(&self, instant: Instant) -> usize {
(instant - self.base).as_nanos() as usize
}
fn get_difference_nanos(&self, other: Instant) -> usize {
self.get_difference(other).as_nanos().try_into().unwrap()
}
fn get_difference(&self, other: Instant) -> Duration {
other - self.base
}
/// Creates a new atomic instant.
///
/// # Examples
///
/// ```rust
/// use atomic_instant_full::AtomicInstant;
/// use std::time::Instant;
///
/// let atomic_instant = AtomicInstant::new(Instant::now());
/// ```
pub fn new(base: Instant) -> AtomicInstant {
AtomicInstant {
base,
offset_nanos: AtomicUsize::new(0),
}
}
/// Creates a new atomic instant at the current time
///
/// # Examples
///
/// ```rust
/// use atomic_instant_full::AtomicInstant;
///
/// let atomic_instant_now = AtomicInstant::now();
/// ```
pub fn now() -> Self {
AtomicInstant {
base: Instant::now(),
offset_nanos: AtomicUsize::new(0),
}
}
/// Stores a value into the atomic instant 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
/// `current`.
///
/// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
/// AtomicUsize
///
/// # Examples
///
/// ```rust
/// use std::sync::atomic::Ordering;
/// use std::time::{Duration, Instant};
///
/// use atomic_instant_full::AtomicInstant;
///
///
/// let now = Instant::now();
/// let now_atomic = AtomicInstant::new(now);
/// let not_now = now + Duration::from_secs(5);
/// let definitely_not_now = now + Duration::from_secs(20);
/// let most_certainly_not_now = now + Duration::from_secs(1000);
/// assert_eq!(now_atomic.compare_exchange(now.clone(), not_now,
/// Ordering::Acquire,
/// Ordering::Relaxed),
/// Ok(now));
/// assert_eq!(now_atomic.load(Ordering::Relaxed), not_now);
/// assert_eq!(now_atomic.compare_exchange(definitely_not_now, most_certainly_not_now,
/// Ordering::SeqCst,
/// Ordering::Acquire),
/// Err(not_now));
/// assert_eq!(now_atomic.load(Ordering::Relaxed), not_now);
///
/// ```
pub fn compare_exchange(
&self,
current: Instant,
new: Instant,
success: Ordering,
failure: Ordering,
) -> Result<Instant, Instant> {
match self.offset_nanos.compare_exchange(
self.offset_nanos_from_instant(current),
self.offset_nanos_from_instant(new),
success,
failure,
) {
Ok(offset_nanos) => Ok(self.instant_from_offset_nanos(offset_nanos)),
Err(offset_nanos) => Err(self.instant_from_offset_nanos(offset_nanos)),
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// Unlike AtomicInstant::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_weak` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
/// AtomicUsize
///
/// # Examples
///
/// ```rust
/// use std::sync::atomic::Ordering;
/// use std::time::{Duration, Instant};
/// use atomic_instant_full::AtomicInstant;
///
/// let now = Instant::now();
/// let atomic = AtomicInstant::new(now);
/// let not_now = now + Duration::from_secs(5);
///
/// let mut old = atomic.load(Ordering::Relaxed);
/// loop {
/// let new = old + Duration::from_secs(8);
/// match atomic.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
/// Ok(_) => break,
/// Err(x) => old = x,
/// }
/// }
/// ```
pub fn compare_exchange_weak(
&self,
current: Instant,
new: Instant,
success: Ordering,
failure: Ordering,
) -> Result<Instant, Instant> {
match self.offset_nanos.compare_exchange_weak(
self.offset_nanos_from_instant(current),
self.offset_nanos_from_instant(new),
success,
failure,
) {
Ok(offset_nanos) => Ok(self.instant_from_offset_nanos(offset_nanos)),
Err(offset_nanos) => Err(self.instant_from_offset_nanos(offset_nanos)),
}
}
/// 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
/// AtomicInstant::compare_exchange respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
/// AtomicUsize
///
/// # Considerations
///
/// This method is not magic; it is not provided by the hardware.
/// It is implemented in terms of AtomicInstant::compare_exchange_weak
/// and suffers from the same drawbacks.
/// In particular, this method will not circumvent the [ABA Problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
///
/// # Examples
///
/// ```rust
/// use atomic_instant_full::AtomicInstant;
/// use std::sync::atomic::Ordering;
/// use std::time::{Duration, Instant};
///
/// let now = Instant::now();
/// let x = AtomicInstant::new(now);
/// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(now));
/// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + Duration::from_secs(1))), Ok(now));
/// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + Duration::from_secs(1))), Ok(now + Duration::from_secs(1)));
/// assert_eq!(x.load(Ordering::SeqCst), now + Duration::from_secs(2));
/// ```
pub fn fetch_update<F: FnMut(Instant) -> Option<Instant>>(
&self,
set_order: Ordering,
fetch_order: Ordering,
mut f: F,
) -> Result<Instant, Instant> {
match self
.offset_nanos
.fetch_update(set_order, fetch_order, |offset_nanos| {
let t = self.instant_from_offset_nanos(offset_nanos);
let r = f(t);
r.map(|offset_nanos| self.offset_nanos_from_instant(offset_nanos))
}) {
Ok(offset_nanos) => Ok(self.instant_from_offset_nanos(offset_nanos)),
Err(offset_nanos) => Err(self.instant_from_offset_nanos(offset_nanos)),
}
}
/// 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.
///
/// # Examples
///
/// ```rust
/// use atomic_instant_full::AtomicInstant;
/// use std::time::Instant;
///
/// let now = Instant::now();
/// let some_instant = AtomicInstant::new(now.clone());
/// assert_eq!(some_instant.into_inner(), now);
/// ```
pub fn into_inner(self) -> Instant {
let offset_nanos = self.offset_nanos.into_inner();
self.base + Duration::from_nanos(offset_nanos as u64)
}
/// Stores a value into the atomic integer, returning the previous value.
///
/// `swap` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
/// AtomicUsize
///
/// # Examples
///
/// ```rust
/// use atomic_instant_full::AtomicInstant;
/// use std::sync::atomic::Ordering;
/// use std::time::{Duration, Instant};
///
/// let now = Instant::now();
/// let some_atomic = AtomicInstant::new(now);
///
/// assert_eq!(some_atomic.swap(now + Duration::from_secs(5), Ordering::Relaxed), now);
/// ```
pub fn swap(&self, val: Instant, order: Ordering) -> Instant {
let r = self
.offset_nanos
.swap(self.offset_nanos_from_instant(val), order);
self.instant_from_offset_nanos(r)
}
/// Loads a value from the atomic instant.
///
/// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Release`] or [`AcqRel`].
///
/// # Examples
///
/// ```rust
/// use atomic_instant_full::AtomicInstant;
/// use std::sync::atomic::Ordering;
/// use std::time::Instant;
///
/// let now = Instant::now();
/// let some_var = AtomicInstant::new(now);
///
/// assert_eq!(some_var.load(Ordering::Relaxed), now);
/// ```
pub fn load(&self, order: Ordering) -> Instant {
let offset_nanos = self.offset_nanos.load(order);
self.instant_from_offset_nanos(offset_nanos)
}
/// Stores a value into the atomic instant.
/// **NOTE** This value cannot go backwards
///
/// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Acquire`] or [`AcqRel`].
///
/// # Examples
///
/// ```rust
/// use atomic_instant_full::AtomicInstant;
/// use std::sync::atomic::Ordering;
/// use std::time::{Duration, Instant};
///
/// let now = Instant::now();
/// let not_now = now + Duration::from_secs(5);
/// let some_var = AtomicInstant::new(now);
///
/// some_var.store(not_now, Ordering::Relaxed);
/// assert_eq!(some_var.load(Ordering::Relaxed), not_now);
/// ```
pub fn store(&self, val: Instant, order: Ordering) {
let offset_nanos = self.offset_nanos_from_instant(val);
self.offset_nanos.store(offset_nanos, order);
}
/// Maximum with the current value.
///
/// Finds the maximum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_man` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// # Examples
///
/// ```rust
/// use atomic_instant_full::AtomicInstant;
/// use std::sync::atomic::Ordering;
/// use std::time::{Duration, Instant};
///
/// let now = Instant::now();
/// let not_now = now + Duration::from_secs(5);
/// let foo = AtomicInstant::new(now);
///
/// assert_eq!(foo.fetch_max(not_now, Ordering::SeqCst), now);
/// assert_eq!(foo.load(Ordering::SeqCst), not_now);
/// ```
pub fn fetch_max(&self, val: Instant, order: Ordering) -> Instant {
self.instant_from_offset_nanos(
self.offset_nanos
.fetch_max(self.get_difference_nanos(val), order),
)
}
/// Minimum with the current value.
///
/// Finds the minimum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// **Note** this function will never find anything before when the base
/// value was initialised.
///
/// `fetch_man` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// # Examples
///
/// ```rust
/// use atomic_instant_full::AtomicInstant;
/// use std::sync::atomic::Ordering;
/// use std::time::{Duration, Instant};
///
/// let now = Instant::now();
/// let not_now = now + Duration::from_secs(5);
/// let foo = AtomicInstant::new(now);
///
/// assert_eq!(foo.fetch_max(not_now, Ordering::SeqCst), now);
/// assert_eq!(foo.load(Ordering::SeqCst), not_now);
///
/// // Cannot find anything before when the value was first initialised
/// let foo = AtomicInstant::new(not_now);
/// assert_eq!(foo.fetch_max(not_now, Ordering::SeqCst), not_now);
/// assert_eq!(foo.load(Ordering::SeqCst), not_now);
/// ```
pub fn fetch_min(&self, val: Instant, order: Ordering) -> Instant {
self.instant_from_offset_nanos(
self.offset_nanos
.fetch_min(self.get_difference_nanos(val), order),
)
}
/// Used to get the original instant without any offsets
///
/// # Examples
///
/// ```rust
/// use atomic_instant_full::AtomicInstant;
/// use std::sync::atomic::Ordering;
/// use std::time::{Duration, Instant};
///
/// let now = Instant::now();
/// let not_now = now + Duration::from_secs(5);
/// let some_var = AtomicInstant::new(not_now);
///
/// some_var.store(not_now, Ordering::Relaxed);
/// assert_eq!(some_var.load(Ordering::Relaxed), not_now);
/// some_var.store(now, Ordering::Relaxed);
/// assert_eq!(some_var.load(Ordering::Relaxed), not_now);
/// ```
pub fn get_base(&self) -> &Instant {
&self.base
}
}
unsafe impl Sync for AtomicInstant {}