How reborrowing works?

⚓ rust    📅 2025-06-05    👤 surdeus    👁️ 1      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: How reborrowing works?

Hi everyone !

I faced with an error in my code:

error[E0382]: borrow of moved value: `buffer`
  --> src/client2.rs:26:22
   |
22 |     fn read(buffer: &mut [u8]) -> anyhow::Result<Vec<u8>> {
   |             ------ move occurs because `buffer` has type `&mut [u8]`, which does not implement the `Copy` trait
23 |         let mut reader = std::io::Cursor::new(buffer);
   |                                               ------ value moved here
...
26 |         let packet = buffer[..pos].to_vec();
   |                      ^^^^^^ value borrowed here after move
   |
help: consider creating a fresh reborrow of `buffer` here
   |
23 |         let mut reader = std::io::Cursor::new(&mut *buffer);

and it seems I do not understand the mechanism of the reborrowing. How it works ?
My code example is:

pub trait BytesRead {
    fn read(buffer: &mut [u8]) -> anyhow::Result<Vec<u8>>;
    fn zeroize(buffer: &mut [u8]) {
        buffer.zeroize();
    }
}

#[derive(Default)]
pub struct PacketReader;
impl BytesRead for PacketReader {
    fn read(buffer: &mut [u8]) -> anyhow::Result<Vec<u8>> {
        let mut reader = std::io::Cursor::new(buffer);
        let _ = Incoming::read(&mut reader)?;
        let pos = reader.position() as usize;
        let packet = buffer[..pos].to_vec();
        Self::zeroize(&mut buffer[..pos]);

        Ok(packet)
    }
}

#[derive(BinRead, Debug)]
#[br(little)]
struct Incoming {
    size: u8,
    #[br(count = size)]
    body: Vec<u8>,
}

and according to compiler's hint I replace this line:

let mut reader = std::io::Cursor::new(buffer);

with this:

let mut reader = std::io::Cursor::new(&mut *buffer);

so this fixed the problem.

Could somebody explain how the reborrowing works ?

5 posts - 5 participants

Read full topic

🏷️ rust_feed