Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this wrapper for !Sync types sound?

Tags:

rust

I sometimes find myself using a !Sync type (eg bumpalo::Bump) as part of the implementation of a type I want to be Sync. Right now I do it with unsafe impl Sync for the outer type, and only touching the inner type in &mut self methods. But is it sound to encapsulate the unsafety with a wrapper like the following? In particular, are the Send bounds correct?

pub struct UnCell<T> {
    value: T
}

unsafe impl<T> Sync for UnCell<T> {}

impl<T> UnCell<T> {
    pub fn new(value: T) -> Self {
        Self { value }
    }
    pub fn into_inner(self) -> T {
        self.value
    }
    pub fn get(&mut self) -> &T {
        &self.value
    }
}
impl<T: Send> UnCell<T> {
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.value
    }
}
like image 432
Dan Avatar asked Sep 10 '25 14:09

Dan


1 Answers

Not just it is sound, there is a pending PR to add a type, Exclusive, that will allow you to do that safely!

[core] add Exclusive to sync - #97629.

You don't even need the Send bound: for a mutable reference to be Send, its referent should also be - and thus if you've got a mutable reference on some thread, you can safely access the referent.

like image 88
Chayim Friedman Avatar answered Sep 13 '25 08:09

Chayim Friedman