Write only buffer

Hello,

I've been using rust for a while now, but I did not write unsafe code yet. However now I need a write only buffer and using a RefCell<Vec<T>> for pushing elements with a shared reference does not feel clean. As I could not find any crate that implements this, I decided to write a custom implementation (Playground link):

use std::cell::UnsafeCell;


#[derive(Debug, Default)]
pub struct WriteOnlyBuf<T> {
    inner: UnsafeCell<Vec<T>>
}

impl<T> WriteOnlyBuf<T> {
    pub fn push(&self, value: T) {
        // SAFETY: No reference to `self.inner` is ever given out
        unsafe {
            (&mut *self.inner.get()).push(value);
        }
    }

    pub fn into_inner(self) -> Vec<T> {
        self.inner.into_inner()
    }
}

pub fn main() {
    let my_buf = WriteOnlyBuf::default();
    let buf_ref = &my_buf;
    let buf_ref_2 = &my_buf;

    buf_ref_2.push(1);
    my_buf.push(2);
    buf_ref.push(3);
}

Miri does not complain, so I guess that is a good sign, but is this an idiomatic implementation? And most importantly, does it violate any unsafe requirements?

Generally, when it comes to UnsafeCell, if the equivalent code using RefCell cannot panic, then the use of UnsafeCell is ok.

2 Likes