title: A cell with interior mutability allowing arbitrary mutation actions
body: <p>Standard <a href="https://doc.rust-lang.org/std/cell/struct.Cell.html" rel="noreferrer">Cell</a> struct provides interior mutability but allows only a few mutation methods such as set(), swap() and replace(). All of these methods change the whole content of the Cell.
  However, sometimes more specific manipulations are needed, for example, to change only a part of data contained in the Cell.</p>
  <p>So I tried to implement some kind of universal Cell, allowing arbitrary data manipulation.
  The manipulation is represented by user-defined closure that accepts a single argument - &amp;mut reference to the interior data of the Cell, so the user itself can deside what to do with the Cell interior. The code below demonstrates the idea:</p>
  <pre><code>use std::cell::UnsafeCell;
  
  struct MtCell&lt;Data&gt;{
      dcell: UnsafeCell&lt;Data&gt;,
  }
  
  impl&lt;Data&gt; MtCell&lt;Data&gt;{
      fn new(d: Data) -&gt; MtCell&lt;Data&gt; {
          return MtCell{dcell: UnsafeCell::new(d)};
      }
  
      fn exec&lt;F, RetType&gt;(&amp;self, func: F) -&gt; RetType where
          RetType: Copy,
          F: Fn(&amp;mut Data) -&gt; RetType 
      {
          let p = self.dcell.get();
          let pd: &amp;mut Data;
          unsafe{ pd = &amp;mut *p; }
          return func(pd);
      }
  }
  
  // test:
  
  type MyCell = MtCell&lt;usize&gt;;
  
  fn main(){
      let c: MyCell = MyCell::new(5);
      println!(&quot;initial state: {}&quot;, c.exec(|pd| {return *pd;}));
      println!(&quot;state changed to {}&quot;, c.exec(|pd| {
          *pd += 10; // modify the interior &quot;in place&quot;
         return *pd;
      }));
  }
  </code></pre>
  <p>However, I have some concerns regarding the code.</p>
  <ol>
  <li><p>Is it safe, i.e can some safe but malicious closure break Rust mutability/borrowing/lifetime rules by using this &quot;universal&quot; cell?
  I consider it safe since lifetime of the interior reference parameter prohibits its exposition beyond the closure call time. But I still have doubts (I'm new to Rust).</p>
  </li>
  <li><p>Maybe I'm re-inventing the wheel and there exist some templates or techniques solving the problem?</p>
  </li>
  </ol>
  <p>Note: I posted the question here (not on code review) as it seems more related to the language rather than code itself (which represents just a concept).</p>
  <p>[EDIT] I'd want zero cost abstraction without possibility of runtime failures, so RefCell is not perfect solution.</p>