Make Compiler Understand that Vec::clear() removes references; Or: Reuse allocation to store temporary references

The only issue I can see on casual inspection is that it's technically perfectly safe for a program to never drop a value. That means that you can have safe code trigger undefined behavior by using the unsafe code incorrectly, which is, at least from a strict safety standpoint, a bad thing.

For improved safety, though, you just need a combination of your original approach and your newer wrapper:

struct VecHolder {
    ptr: *mut Message<'static>,
    capacity: usize,
}

impl VecHolder {
    pub fn new() -> Self {
        Self {
            ptr: std::ptr::null_mut(),
            capacity: 0,
        }
    }

    pub fn take<'a>(&mut self) -> Vec<Message<'a>> {
        if self.capacity == 0 {
            return Vec::new();
        }
        let ptr: *mut Message<'a> = unsafe { std::mem::transmute(self.ptr) };
        let capacity = self.capacity;
        self.capacity = 0;
        self.ptr = std::ptr::null_mut();
        unsafe { Vec::from_raw_parts(ptr, 0, capacity) }
    }

    pub fn give<'a>(&mut self, mut data: Vec<Message<'a>>) {
        data.clear();
        let ptr: *mut Message<'static> = unsafe { std::mem::transmute(data.as_mut_ptr()) };
        let capacity = data.capacity();
        std::mem::forget(data);
        self.clear();
        self.ptr = ptr;
        self.capacity = capacity;
    }

    pub fn clear(&mut self) {
        if self.capacity > 0 {
            std::mem::drop(self.take());
        }
    }
}

impl Drop for VecHolder {
    fn drop(&mut self) {
        self.clear()
    }
}

#[derive(Debug)]
struct Message<'a>(&'a str);

struct SharedState {
    msg_buf: VecHolder,
}

impl SharedState {
    pub fn dispatch_events(&mut self, data: &[&str]) {
        let mut msg_buf = self.msg_buf.take();
        // push a bunch of messages
        for m in data.iter() {
            msg_buf.push(Message(m));
        }
        println!("Messages: {:?}", &msg_buf);
        self.msg_buf.give(msg_buf);
    }
}

fn main() {
    let mut state = SharedState {
        msg_buf: VecHolder::new(),
    };
    state.dispatch_events(&["a", "b", "c", "d"]);
    state.dispatch_events(&["e", "f", "g", "h"]);
}

Disclaimer: I'm not a seasoned Rust expert. I put this code through only very minimal testing, and I'm also writing while tired. This could very easily be even more unsafe than your gist if it doesn't work the way I think it does.

That being said, if this actually works as intended, it would be interesting to generalize it to support arbitrary types. That'll probably be non-trivial to do safely, though.