Skip to content

Exclusive Reborrowing Brainstorming

MaulingMonkey edited this page Feb 16, 2024 · 2 revisions

The Basics

struct S { pub a: u32, pub b: u32 }

  • Ideal "by-value borrow" is valrow::Valrow<'s, S> as stands ✔️
  • Maybe in scope for #[derive(valrow::Borrowable)]
  • valrow::ValrowMut<S> would gains nothing but making a and b individually modifiable, which would be a footgun as the values are destined to be discarded.

Indirect Interior Mutability

struct S { pub a: Arc<u32>, pub b: ABox<u32> }

Ideal "by-value borrow"s:

Adding a Vec<u32> would break ABI but encourage:

  • struct S_exclusive<'s> { ..., pub c: &'s mut [u32] }
  • struct S_shared <'s> { ..., pub c: &'s [u32] }

Direct Interior Mutability

The ideal "by-value borrow" is something that Derefs into something other than S, and can't Deref back into S. Into<S> might be an option. valrow::ValrowMut / DerefMut would encourage modifying a discardable field value, which is lame / to be avoided.

struct S { pub a: Cell<u32>, pub b: u32 }
struct S { pub a: AtomicU32, pub b: u32 }

  • struct S_partial { pub b: u32 } - unusable field discarded
  • struct S_copied { pub a: u32, pub b: u32 } - ❌ freezes a at possibly stale value (other regular borrows might exist)
  • struct S_mixed { pub a: &Cell<u32>, pub b: u32 } - mix of by-reference and by-value captures
  • struct S_padded { _a: Opaque<u32>, pub b: u32 } - ABI compatible but supressed (only works if Field: Copy)

struct S { pub a: RefCell<u32>, pub b: u32 }
struct S { pub a: Mutex<u32>, pub b: u32 }
struct S { pub a: RwLock<u32>, pub b: u32 }

  • Ideal "by-value borrow" Derefs into something other than S.
    • struct S_partial { pub b: u32 } - unusable field discarded
    • struct S_copied { pub a: u32, pub b: u32 } - ❌ freezes a at possibly stale value, panic hazard
    • struct S_mixed { pub a: &RefCell<u32>, pub b: u32 } - mix of by-reference and by-value captures
    • struct S_padded { _a: ???, pub b: u32 } - ❌ can't sanely specify _a's layout while remaining Copy.
  • Anything which may convert Into<S> would require a cell.borrow().clone() which is a panic hazard.