Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

glib: Add upgrade_or_insert{_with} to WeakRefs #1249

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions glib/src/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3429,6 +3429,35 @@ impl<T: ObjectType> WeakRef<T> {
}
}
}

// rustdoc-stripper-ignore-next
/// Try to upgrade this weak reference to a strong reference.
///
/// If the stored object was already destroyed or no object was set, the
/// reference is updated to `value`, which is then returned
#[inline]
pub fn upgrade_or_insert(&self, value: T) -> T {
self.upgrade_or_insert_with(|| value)
}

// rustdoc-stripper-ignore-next
/// Try to upgrade this weak reference to a strong reference.
///
/// If the stored object was already destroyed or no object was set, the
/// reference is updated to the result of `f`, which is then returned
#[inline]
pub fn upgrade_or_insert_with<F>(&self, f: F) -> T
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is unfortunately racy if called from multiple threads at once. That at least should be documented.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, yes. I suppose we can't do much about that without new upstream API? bother.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think so

where
F: FnOnce() -> T,
{
if let Some(object) = self.upgrade() {
object
} else {
let object = f();
self.set(Some(&object));
object
}
}
}

impl<T: ObjectType> Drop for WeakRef<T> {
Expand Down
Loading