Rust:在“Copy”类型中使用“std::ptr::write_volatile”实现内部可变性的安全性(例如,没有“UnsafeCell”)

问题描述 投票:0回答:1

我正在尝试在

Copy
值类型中实现内部可变性(用于缓存目的)。

问题是,据我所知,可用于内部可变性的类型(例如

UnsafeCell
和相关类型、原子类型)都不允许
Copy
特征。 顺便说一句,这是稳定的 Rust

我的问题是:在这种情况下使用

std::ptr::write_volatile
std::ptr::read_volatile
来实现内部可变性有多安全?

具体来说,我有这段代码,我想知道其中是否有任何陷阱或未定义的行为:

use std::fmt::{Debug, Display, Formatter};

#[derive(Copy, Clone)]
pub struct CopyCell<T: Copy> {
    value: T,
}

impl<T: Copy> CopyCell<T> {
    pub fn new(value: T) -> Self {
        Self { value }
    }

    pub fn get(&self) -> T {
        unsafe { std::ptr::read_volatile(&self.value) }
    }

    pub fn set(&self, value: T) {
        let ptr = &self.value as *const T;
        let ptr = ptr as *mut T;
        unsafe { std::ptr::write_volatile(ptr, value) }
    }
}

impl<T: Default + Copy> Default for CopyCell<T> {
    fn default() -> Self {
        CopyCell { value: T::default() }
    }
}

impl<T: Display + Copy> Display for CopyCell<T> {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        let value = self.get();
        write!(f, "{value}")
    }
}

impl<T: Debug + Copy> Debug for CopyCell<T> {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        let value = self.get();
        write!(f, "{value:?}")
    }
}

我的目标是使用它在值类型内实现本地缓存(例如某种记忆)。我特别想要

Copy
语义(即而不是
Clone
),因为它们对于我想要实现的目标具有更好的人体工程学原理。

这是一个示例用法:

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn simple_test() {
        let a = CopyCell::default();
        let b = CopyCell::new(42);

        assert_eq!(a.get(), 0);
        assert_eq!(b.get(), 42);

        a.set(123);
        b.set(b.get() * 10);
        assert_eq!(a.get(), 123);
        assert_eq!(b.get(), 420);

        let a1 = a;
        let b1 = b;

        a.set(0);
        b.set(0);

        assert_eq!(a1.get(), 123);
        assert_eq!(b1.get(), 420);
    }

    #[test]
    fn cached_compute() {
        let a = CachedCompute::new(10);
        assert_eq!(a.compute(), 100);
        assert_eq!(a.compute(), 100);

        let b = a;
        assert_eq!(b.compute(), 100);
    }

    #[derive(Copy, Clone)]
    pub struct CachedCompute {
        source: i32,
        result: CopyCell<Option<i32>>,
    }

    impl CachedCompute {
        pub fn new(source: i32) -> Self {
            Self {
                source,
                result: Default::default(),
            }
        }

        pub fn compute(&self) -> i32 {
            if let Some(value) = self.result.get() {
                value
            } else {
                let result = self.source * self.source; // assume this is expensive
                self.result.set(Some(result));
                result
            }
        }
    }
}

上面的代码乍一看是有效的。但我想知道这种方法是否存在任何潜在的问题,这些问题在表面上可能并不明显。

我对 Rust 的内存模型、编译器优化、机器代码级语义等没有足够的了解,在这种情况下可能会导致问题。

即使这种方法适用于当前平台,我想知道将来是否会遇到有关未定义行为的潜在问题。

optimization rust compiler-optimization undefined-behavior
1个回答
1
投票

没有。如果没有

UnsafeCell
,Rust 绝对不可能实现内部可变性。

您的代码是 UB 且 Miri 如此标记它:

error: Undefined Behavior: attempting a write access using <1698> at alloc880[0x0], but that tag only grants SharedReadOnly permission for this location
  --> src/main.rs:20:18
   |
20 |         unsafe { std::ptr::write_volatile(ptr, value) }
   |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |                  |
   |                  attempting a write access using <1698> at alloc880[0x0], but that tag only grants SharedReadOnly permission for this location
   |                  this error occurs as part of an access at alloc880[0x0..0x4]
   |
   = help: this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental
   = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information
help: <1698> was created by a SharedReadOnly retag at offsets [0x0..0x4]
  --> src/main.rs:18:19
   |
18 |         let ptr = &self.value as *const T;
   |                   ^^^^^^^^^^^
   = note: BACKTRACE (of the first span):
   = note: inside `CopyCell::<i32>::set` at src/main.rs:20:18: 20:54
note: inside `main`
  --> src/main.rs:51:5
   |
51 |     a.set(123);
   |     ^^^^^^^^^^

通过使用 volatile,你只是欺骗了优化器,所以你的代码“有效”,但它仍然是 UB。

人们确实想要一个

UnsafeCell
,即
Copy
,但现在添加它是一个问题,因为人们依靠
T: Copy
来表示
T
内部没有
UnsafeCell
。不过,也许有一天会添加它。

© www.soinside.com 2019 - 2024. All rights reserved.