Skip to content

Commit 4abe1b7

Browse files
committed
feat(atomic): add try_update and update
1 parent 569baaf commit 4abe1b7

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

src/atomic/unsync.rs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,33 @@ impl AtomicBool {
132132
}
133133
}
134134

135+
/// Fetches the value, and applies a function to it that returns an optional
136+
/// new value. Returns a `Result` of `Ok(previous_value)` if the function
137+
/// returned `Some(_)`, else `Err(previous_value)`.
138+
pub fn try_update(
139+
&self,
140+
_: Ordering,
141+
_: Ordering,
142+
mut f: impl FnMut(bool) -> Option<bool>,
143+
) -> Result<bool, bool> {
144+
let curr = self.v.get();
145+
if let Some(new) = f(curr) {
146+
self.v.set(new);
147+
Ok(curr)
148+
} else {
149+
Err(curr)
150+
}
151+
}
152+
153+
/// Fetches the value, and applies a function to it that returns a new
154+
/// value. Returns the previous_value.
155+
pub fn update(&self, _: Ordering, _: Ordering, mut f: impl FnMut(bool) -> bool) -> bool {
156+
let curr = self.v.get();
157+
let new = f(curr);
158+
self.v.set(new);
159+
curr
160+
}
161+
135162
/// Bitwise "and" with the current value.
136163
///
137164
/// Performs a bitwise "and" operation on the current value and the argument
@@ -306,6 +333,33 @@ macro_rules! atomic_int {
306333
}
307334
}
308335

336+
/// Fetches the value, and applies a function to it that returns an optional
337+
/// new value. Returns a `Result` of `Ok(previous_value)` if the function
338+
/// returned `Some(_)`, else `Err(previous_value)`.
339+
pub fn try_update(
340+
&self,
341+
_: Ordering,
342+
_: Ordering,
343+
mut f: impl FnMut($i) -> Option<$i>,
344+
) -> Result<$i, $i> {
345+
let curr = self.v.get();
346+
if let Some(new) = f(curr) {
347+
self.v.set(new);
348+
Ok(curr)
349+
} else {
350+
Err(curr)
351+
}
352+
}
353+
354+
/// Fetches the value, and applies a function to it that returns a new value. Returns the
355+
/// previous_value.
356+
pub fn update(&self, _: Ordering, _: Ordering, mut f: impl FnMut($i) -> $i) -> $i {
357+
let curr = self.v.get();
358+
let new = f(curr);
359+
self.v.set(new);
360+
curr
361+
}
362+
309363
/// Adds to the current value, returning the previous value.
310364
pub fn fetch_add(&self, val: $i, _: Ordering) -> $i {
311365
self.v.replace(self.v.get() + val)

0 commit comments

Comments
 (0)