Skip to content

Commit 1b6b6aa

Browse files
authored
Replace AtomicUsize with Cell<usize> in the recursion counter (apache#1098)
1 parent c86508b commit 1b6b6aa

1 file changed

Lines changed: 10 additions & 9 deletions

File tree

src/parser/mod.rs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ macro_rules! return_ok_if_some {
6161
#[cfg(feature = "std")]
6262
/// Implementation [`RecursionCounter`] if std is available
6363
mod recursion {
64-
use core::sync::atomic::{AtomicUsize, Ordering};
64+
use std::cell::Cell;
6565
use std::rc::Rc;
6666

6767
use super::ParserError;
@@ -70,12 +70,11 @@ mod recursion {
7070
/// each call to `try_decrease()`, when it reaches 0 an error will
7171
/// be returned.
7272
///
73-
/// Note: Uses an Rc and AtomicUsize in order to satisfy the Rust
73+
/// Note: Uses an Rc and Cell in order to satisfy the Rust
7474
/// borrow checker so the automatic DepthGuard decrement a
75-
/// reference to the counter. The actual value is not modified
76-
/// concurrently
75+
/// reference to the counter.
7776
pub(crate) struct RecursionCounter {
78-
remaining_depth: Rc<AtomicUsize>,
77+
remaining_depth: Rc<Cell<usize>>,
7978
}
8079

8180
impl RecursionCounter {
@@ -94,29 +93,31 @@ mod recursion {
9493
/// Returns a [`DepthGuard`] which will adds 1 to the
9594
/// remaining depth upon drop;
9695
pub fn try_decrease(&self) -> Result<DepthGuard, ParserError> {
97-
let old_value = self.remaining_depth.fetch_sub(1, Ordering::SeqCst);
96+
let old_value = self.remaining_depth.get();
9897
// ran out of space
9998
if old_value == 0 {
10099
Err(ParserError::RecursionLimitExceeded)
101100
} else {
101+
self.remaining_depth.set(old_value - 1);
102102
Ok(DepthGuard::new(Rc::clone(&self.remaining_depth)))
103103
}
104104
}
105105
}
106106

107107
/// Guard that increass the remaining depth by 1 on drop
108108
pub struct DepthGuard {
109-
remaining_depth: Rc<AtomicUsize>,
109+
remaining_depth: Rc<Cell<usize>>,
110110
}
111111

112112
impl DepthGuard {
113-
fn new(remaining_depth: Rc<AtomicUsize>) -> Self {
113+
fn new(remaining_depth: Rc<Cell<usize>>) -> Self {
114114
Self { remaining_depth }
115115
}
116116
}
117117
impl Drop for DepthGuard {
118118
fn drop(&mut self) {
119-
self.remaining_depth.fetch_add(1, Ordering::SeqCst);
119+
let old_value = self.remaining_depth.get();
120+
self.remaining_depth.set(old_value + 1);
120121
}
121122
}
122123
}

0 commit comments

Comments
 (0)