关于我的类似RefCell的结构上的rust:borrow_mut()不起作用

borrow_mut() on my RefCell-like structure doesn't work

我尝试编写自己的类似于RefCell的可变内存位置,但没有运行时借用检查(无开销)。 我采用了RefCell(和RefRefMut)的代码体系结构。 我可以毫无问题地调用.borrow(),但是如果我调用.borrow_mut(),那么rust编译器会显示cannot borrow as mutable。 我没有看到问题,我的.borrow_mut() impl看起来不错吗?

失败的代码:

1
2
3
4
5
6
7
8
let real_refcell= Rc::from(RefCell::from(MyStruct::new()));
let nooverhead_refcell = Rc::from(NORefCell::from(MyStruct::new()));

// works
let refmut_refcell = real_refcell.borrow_mut();

// cannot borrow as mutable
let refmut_norefcell = nooverhead_refcell.borrow_mut();

norc.rs(无开销RefCell)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
use crate::norc_ref::{NORefMut, NORef};
use std::cell::UnsafeCell;
use std::borrow::Borrow;

#[derive(Debug)]
pub struct NORefCell<T: ?Sized> {
    value: UnsafeCell< T >
}

impl< T > NORefCell< T > {

    pub fn from(t: T) -> NORefCell< T > {
        NORefCell {
            value: UnsafeCell::from(t)
        }
    }

    pub fn borrow(&self) -> NORef<'_, T> {
        NORef {
            value: unsafe { &*self.value.get() }
        }
    }

    pub fn borrow_mut(&mut self) -> NORefMut<'_, T> {
        NORefMut {
            value: unsafe { &mut *self.value.get() }
        }
    }

}

norc_ref.rs(NORefCell.borrow[_mut]()返回的数据结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
use std::ops::{Deref, DerefMut};

#[derive(Debug)]
pub struct NORef<'b, T: ?Sized + 'b> {
    pub value: &'b T,
}

impl<T: ?Sized> Deref for NORef<'_, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &T {
        self.value
    }
}

/// No Overhead Ref Cell: Mutable Reference
#[derive(Debug)]
pub struct NORefMut<'b, T: ?Sized + 'b> {
    pub value: &'b mut T,
}

impl<T: ?Sized> Deref for NORefMut<'_, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &T {
        self.value
    }
}

impl<T: ?Sized> DerefMut for NORefMut<'_, T> {

    #[inline]
    fn deref_mut(&mut self) -> &mut T {
        self.value
    }
}


NORefCell::borrow_mut()&mut self,在包装它的Rc上需要一个DerefMut。 这是行不通的,因为Rc不会仅仅通过很好地询问就给出可变引用(您需要它检查引用计数是否恰好是1,否则将有多个可变借项)。

borrow_mut必须采用&self而不是&mut self

如我的评论中所述:您基本上在做什么是围绕UnsafeCell提供安全的抽象。 这是非常危险的。 注意有关UnsafeCell的文档:

The compiler makes optimizations based on the knowledge that &T is not mutably aliased or mutated, and that &mut T is unique. UnsafeCell is the only core language feature to work around the restriction that &T may not be mutated.

您正在为这个强大的对象提供一个瘦包装器,在API边界上没有unsafe。" No-overhead-RefCell"实际上是"无触发器的护脚枪"。 它确实有效,但仍会警告其危险。