Simplify shared-from-this pattern

This commit is contained in:
The0x539
2024-03-08 18:08:55 -06:00
committed by Johannes Altmanninger
parent e5f83cd9a7
commit 1de7ebcf68
2 changed files with 7 additions and 39 deletions

View File

@@ -1,6 +1,5 @@
use crate::flog::FLOG;
use std::cell::{Ref, RefCell, RefMut};
use std::rc::{Rc, Weak};
use std::cell::{Ref, RefMut};
use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering};
use std::sync::MutexGuard;
@@ -53,30 +52,6 @@ pub fn store(&self, value: &'static &'static T) {
}
}
pub struct SharedFromThisBase<T> {
weak: RefCell<Weak<T>>,
}
impl<T> SharedFromThisBase<T> {
pub fn new() -> SharedFromThisBase<T> {
SharedFromThisBase {
weak: RefCell::new(Weak::new()),
}
}
pub fn initialize(&self, r: &Rc<T>) {
*self.weak.borrow_mut() = Rc::downgrade(r);
}
}
pub trait SharedFromThis<T> {
fn get_base(&self) -> &SharedFromThisBase<T>;
fn shared_from_this(&self) -> Rc<T> {
self.get_base().weak.borrow().upgrade().unwrap()
}
}
pub struct DebugRef<'a, T>(Ref<'a, T>);
impl<'a, T> DebugRef<'a, T> {

View File

@@ -15,7 +15,7 @@
use crate::fds::open_cloexec;
use crate::flog::FLOGF;
use crate::function;
use crate::global_safety::{RelaxedAtomicBool, SharedFromThis, SharedFromThisBase};
use crate::global_safety::RelaxedAtomicBool;
use crate::io::IoChain;
use crate::job_group::MaybeJobId;
use crate::operation_context::{OperationContext, EXPANSION_LIMIT_DEFAULT};
@@ -42,7 +42,7 @@
use std::os::fd::{AsRawFd, OwnedFd, RawFd};
use std::os::unix::prelude::OsStrExt;
use std::pin::Pin;
use std::rc::Rc;
use std::rc::{Rc, Weak};
use std::sync::{
atomic::{AtomicIsize, AtomicU64, Ordering},
Arc,
@@ -295,7 +295,7 @@ pub enum ParserStatusVar {
pub type ParserRef = Rc<Parser>;
pub struct Parser {
base: SharedFromThisBase<Parser>,
this: Weak<Self>,
/// The current execution context.
execution_context: RefCell<Option<ParseExecutionContext>>,
@@ -335,17 +335,11 @@ pub struct Parser {
pub global_event_blocks: AtomicU64,
}
impl SharedFromThis<Parser> for Parser {
fn get_base(&self) -> &SharedFromThisBase<Parser> {
&self.base
}
}
impl Parser {
/// Create a parser
pub fn new(variables: EnvStackRef, is_principal: bool) -> ParserRef {
let result = Rc::new(Self {
base: SharedFromThisBase::new(),
let result = Rc::new_cyclic(|this: &Weak<Self>| Self {
this: Weak::clone(this),
execution_context: RefCell::default(),
job_list: RefCell::default(),
wait_handles: RefCell::new(WaitHandleStore::new()),
@@ -372,7 +366,6 @@ pub fn new(variables: EnvStackRef, is_principal: bool) -> ParserRef {
}
}
result.base.initialize(&result);
result
}
@@ -1075,7 +1068,7 @@ pub fn set_syncs_uvars(&self, flag: bool) {
/// \return a shared pointer reference to this parser.
pub fn shared(&self) -> ParserRef {
self.shared_from_this()
self.this.upgrade().unwrap()
}
/// \return the operation context for this parser.